我收到一段代码的警告,但 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》第 4 版一书 -

In C and in older C++ code, you could assign a string literal to a non-const char*:

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

It would obviously be unsafe to accept that assignment. It was (and is) a source of subtle errors, so please don’t grumble too much if some old code fails to compile for this reason.

这表明,上面的代码应该会出错,但我却收到了警告。

    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 标志,使编译器拒绝无效代码。

Live example