Share via


編譯器警告 (層級 4) C4868

' file line_number )' 編譯器可能不會以大括弧初始化運算式清單強制執行由左至右的評估順序

大括弧初始化運算式清單的專案會以從左至右的順序進行評估。 編譯器無法保證此順序有兩種情況:第一個情況是當某些元素是以值傳遞的物件時:第二個是使用 /clr 編譯時,有些元素是 物件的欄位,或是陣列元素。 當編譯器無法保證由左至右評估時,它會發出警告 C4868。

這個警告可能是因為 Visual Studio 2015 Update 2 所完成的編譯器一致性工作而產生。 在 Visual Studio 2015 Update 2 之前編譯的程式碼現在可以產生 C4868。

此警告預設為關閉。 使用 /Wall 來啟用此警告。

若要解決這個警告,請先考慮是否需要對初始化運算式清單元素進行從左至右評估,例如評估元素時,可能會產生順序相依的副作用。 在許多情況下,評估元素的順序不會有可觀察的效果。

如果評估順序必須由左至右,請考慮是否可以改為以傳址方式 const 傳遞元素。 這類變更可排除下列程式碼範例中的警告。

範例

此範例會產生 C4868,並示範修正方法:

// C4868.cpp
// compile with: /c /Wall
#include <cstdio>

class HasCopyConstructor
{
public:
    int x;

    HasCopyConstructor(int x): x(x) {}

    HasCopyConstructor(const HasCopyConstructor& h): x(h.x)
    {
        printf("Constructing %d\n", h.x);
    }
};

class TripWarning4868
{
public:
    // note that taking "HasCopyConstructor" parameters by-value will trigger copy-construction.
    TripWarning4868(HasCopyConstructor a, HasCopyConstructor b) {}

    // This variation will not trigger the warning:
    // TripWarning4868(const HasCopyConstructor& a, const HasCopyConstructor& b) {}
};

int main()
{
    HasCopyConstructor a{1};
    HasCopyConstructor b{2};

    // the warning will indicate the below line, the usage of the braced initializer list.
    TripWarning4868 warningOnThisLine{a, b};
};