繁体   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