我完全同意其他答案,我只想补充一点,g++(至少 4.4 版)实际上将这些不推荐使用的转换捕获为任何警告级别的警告(如果以前的版本默认情况下不这样做,可能你必须提出警告等级):
#include <iostream>
using namespace std;
void WithConst(const char * Str)
{
cout<<Str<<endl;
}
void WithoutConst_NoEdit(char * Str)
{
cout<<Str<<endl;
}
void WithoutConst_Edit(char * Str)
{
*Str='a';
cout<<Str<<endl;
}
int main()
{
WithConst("Test");
WithoutConst_NoEdit("Test");
WithoutConst_Edit("Test");
return 0;
}
matteo@teoubuntu:~/cpp/test$ g++ --version
g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
matteo@teoubuntu:~/cpp/test$ g++ -O3 lit_const_corr.cpp -o lit_const_corr.x
lit_const_corr.cpp: In function ‘int main()’:
lit_const_corr.cpp:24: warning: deprecated conversion from string constant to ‘char*’
lit_const_corr.cpp:25: warning: deprecated conversion from string constant to ‘char*’
matteo@teoubuntu:~/cpp/test$ g++ -O3 -Wall lit_const_corr.cpp -o lit_const_corr.x
lit_const_corr.cpp: In function ‘int main()’:
lit_const_corr.cpp:24: warning: deprecated conversion from string constant to ‘char*’
lit_const_corr.cpp:25: warning: deprecated conversion from string constant to ‘char*’
matteo@teoubuntu:~/cpp/test$ g++ -O3 -Wall -Wextra -ansi -pedantic lit_const_corr.cpp -o lit_const_corr.x
lit_const_corr.cpp: In function ‘int main()’:
lit_const_corr.cpp:24: warning: deprecated conversion from string constant to ‘char*’
lit_const_corr.cpp:25: warning: deprecated conversion from string constant to ‘char*’
此外,还有一些有趣的事情发生在幕后:如果我在没有优化的情况下编译它,它“只是按照代码所说的”,所以它崩溃了,因为它试图写入只读内存位置:
matteo@teoubuntu:~/cpp/test$ g++ -Wall -Wextra -ansi -pedantic lit_const_corr.cpp -o lit_const_corr.x
lit_const_corr.cpp: In function ‘int main()’:
lit_const_corr.cpp:24: warning: deprecated conversion from string constant to ‘char*’
lit_const_corr.cpp:25: warning: deprecated conversion from string constant to ‘char*’
matteo@teoubuntu:~/cpp/test$ ./lit_const_corr.x
Test
Test
Segmentation fault
但是,如果您打开优化器,则不会发生崩溃:
matteo@teoubuntu:~/cpp/test$ g++ -O3 -Wall -Wextra -ansi -pedantic lit_const_corr.cpp -o lit_const_corr.x
lit_const_corr.cpp: In function ‘int main()’:
lit_const_corr.cpp:24: warning: deprecated conversion from string constant to ‘char*’
lit_const_corr.cpp:25: warning: deprecated conversion from string constant to ‘char*’
matteo@teoubuntu:~/cpp/test$ ./lit_const_corr.x
Test
Test
Test
我想这是由于一些神奇的优化技巧,但我不明白为什么要应用它;任何想法?
附录
当我声明一个 char* foo = "bar" 它实际上抱怨。但是当我声明 char foo[] = "bar" 它没有
嘿,注意不要混淆这两件事:与
char * foo = "bar";
您正在声明一个指向 char 的指针,并为其分配文字“bar”的地址,该地址实际上存储在某个只读内存位置(通常它是映射到内存中的可执行文件的一部分)。相反,与
char foo[]="bar";
您正在为 chars 数组声明和分配 RW 内存(在堆栈或其他地方,取决于上下文),该数组使用“bar”值初始化,但它与字符串表完全无关,它是完全合法地更改该字符串。