/Zc:strictStrings
(停用字串常數值型別轉換)
指定時,對於使用字串常值初始的指標,編譯器需要嚴格的 const
限定一致性。
語法
/Zc:strictStrings
[-
]
備註
如果 /Zc:strictStrings
指定 ,則編譯器會根據宣告,強制執行字串常值的標準 C++ const
限定性,做為類型 'array of const char
' 或 'array of const wchar_t
'。 字串常值不可變,如果嘗試修改其內容,則會導致執行階段存取違規錯誤。 您必須將字串指標宣告為 const
,以使用字串常值來對其進行初始化,或者使用明確的 const_cast
,對非 const
指標進行初始化。 根據預設,如果 /Zc:strictStrings-
指定 ,編譯器不會針對使用字串常值初始化的字串指標強制執行標準 C++ const
限定性。
選項 /Zc:strictStrings
預設為關閉。 編譯 /permissive-
程式選項會隱含地設定這個選項,但可以使用 來覆寫 /Zc:strictStrings-
。
/Zc:strictStrings
使用 選項來防止編譯不正確的程式碼。 此範例顯示簡單的宣告錯誤如何導致執行階段損毀:
// strictStrings_off.cpp
// compile by using: cl /W4 strictStrings_off.cpp
int main() {
wchar_t* str = L"hello";
str[2] = L'a'; // run-time error: access violation
}
啟用 時 /Zc:strictStrings
,相同的程式碼會在 宣告 str
中報告錯誤。
// strictStrings_on.cpp
// compile by using: cl /Zc:strictStrings /W4 strictStrings_on.cpp
int main() {
wchar_t* str = L"hello"; // error: Conversion from string literal
// loses const qualifier
str[2] = L'a';
}
如果您使用 auto
,來宣告字串指標,則編譯器會為您建立正確的 const
指標類型宣告。 如果嘗試修改 const
指標的內容,則編譯器會報告錯誤。
注意
Visual Studio 2013 中的 C++ 標準程式庫不支援 /Zc:strictStrings
偵錯組建中的編譯器選項。 如果您在組建輸出中看到數 個 C2665 錯誤,這可能是原因。
如需 Visual C++ 中一致性問題的詳細資訊,請參閱 Nonstandard Behavior。
在 Visual Studio 開發環境中設定這個編譯器選項
開啟專案的 [屬性頁] 對話方塊。 如需詳細資料,請參閱在 Visual Studio 中設定 C ++ 編譯器和組建屬性。
選取 [組態屬性]>[C/C++]>[命令列] 屬性頁。
修改 [其他選項] 屬性以包含
/Zc:strictStrings
,然後選擇 [ 確定 ]。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應