簡體   English   中英

我收到一段代碼的警告,但 bjarne stroustrup 的 c++ 書說它應該是一個錯誤。 這里有什么?

[英]I am getting the warning for a piece of code, but the c++ book by bjarne stroustrup is saying it should be an error. what is right here?

根據書籍 The C++ Programming Language, 4th Edition -

在 C 和較舊的 C++ 代碼中,您可以將字符串文字分配給非常量 char*:

 void f() { char* p = "Plato"; // error, but accepted in pre-C++11-standard code p[4] = 'e'; // error : assignment to const }

接受這個任務顯然是不安全的。 它曾經(並且現在)是細微錯誤的來源,因此如果某些舊代碼因此無法編譯,請不要抱怨太多。

它表明,上面的代碼應該出錯,但我收到了警告。

    21:22:38 **** Incremental Build of configuration Debug for project study ****
Info: Internal Builder is used for build
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\study.o" "..\\src\\study.cpp" 
..\src\study.cpp: In function 'void f()':
..\src\study.cpp:10:13: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

GCC 編譯器在默認情況下有些寬松,並允許進行一些擴展,例如隱式轉換字符串的常量性。

很可能添加此擴展是為了保持與 C 的兼容性。

要禁用這些擴展,只需添加--pedantic-errors標志,這將使編譯器拒絕無效代碼。

活生生的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM