[英]what is the wrong with this example in the c++ book of Bjarne Stroustrup
[英]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.