/Zc:rvalueCast (強制型別轉換規則)
/Zc:rvalueCast
指定 選項時,編譯器會正確地將右值參考類型識別為轉換作業的結果。 其行為符合 C++11 標準。 未指定 選項時,編譯器行為與 Visual Studio 2012 中的行為相同。
語法
/Zc:rvalueCast
/Zc:rvalueCast-
備註
如果 /Zc:rvalueCast
指定 ,則編譯器會遵循 C++11 標準的第 5.4 節,並只將產生非參考型別的轉換運算式和產生非函式型別右值參考的轉換運算式視為右值型別。 根據預設,或 /Zc:rvalueCast-
如果指定,編譯器不符合規範,並且將所有產生右值參考的轉換運算式視為右值。 為了符合規範,以及消除轉換的使用錯誤,我們建議您使用 /Zc:rvalueCast
。
根據預設, /Zc:rvalueCast
會關閉 ( /Zc:rvalueCast-
)。 /permissive- 編譯器選項會隱含地設定這個選項,但可以使用 來覆寫 /Zc:rvalueCast-
它。
如果您將轉換運算式當做引數傳遞至採用右值參考類型的函式,請使用 /Zc:rvalueCast
。 當編譯器錯誤判斷轉換運算式的類型時,預設行為會導致編譯器錯誤 C2664 。 本範例會在未指定時 /Zc:rvalueCast
,在正確的程式碼中顯示編譯器錯誤:
// Test of /Zc:rvalueCast
// compile by using:
// cl /c /Zc:rvalueCast- make_thing.cpp
// cl /c /Zc:rvalueCast make_thing.cpp
#include <utility>
template <typename T>
struct Thing {
// Construct a Thing by using two rvalue reference parameters
Thing(T&& t1, T&& t2)
: thing1(t1), thing2(t2) {}
T& thing1;
T& thing2;
};
// Create a Thing, using move semantics if possible
template <typename T>
Thing<T> make_thing(T&& t1, T&& t2)
{
return (Thing<T>(std::forward<T>(t1), std::forward<T>(t2)));
}
struct Test1 {
long a;
long b;
Thing<long> test() {
// Use identity casts to create rvalues as arguments
return make_thing(static_cast<long>(a), static_cast<long>(b));
}
};
適當時,預設編譯器行為可能不會報告錯誤 C2102。 在此範例中,如果未指定身分識別轉換 /Zc:rvalueCast
所建立的右值位址,則編譯器不會回報錯誤:
int main() {
int a = 1;
int *p = &a; // Okay, take address of lvalue
// Identity cast creates rvalue from lvalue;
p = &(int)a; // problem: should cause C2102: '&' requires l-value
}
如需 Visual C++ 中一致性問題的詳細資訊,請參閱 Nonstandard Behavior。
在 Visual Studio 開發環境中設定這個編譯器選項
開啟專案的 [屬性頁] 對話方塊。 如需詳細資料,請參閱在 Visual Studio 中設定 C ++ 編譯器和組建屬性。
選取 [ 組態屬性 > C/C++ > 語言] 屬性頁。
將 [ 強制執行類型轉換規則] 屬性設定為
/Zc:rvalueCast
或/Zc:rvalueCast-
。 選擇 [確定 ] 或 [ 套用 ] 以儲存您的變更。
另請參閱
意見反映
https://aka.ms/ContentUserFeedback。
即將推出:我們會在 2024 年淘汰 GitHub 問題,並以全新的意見反應系統取代並作為內容意見反應的渠道。 如需更多資訊,請參閱:提交及檢視以下的意見反映: