您的位置:首页 > 其它

[Warning] deprecated conversion from string constant to 'char*' 原因

2016-09-17 23:40 323 查看
C++代码:

char *ss = "2cc5";
会提示说[Warning] deprecated conversion from string constant to 'char*' 。

来看看stackoverflow里面的一个回答:



Why? Well, C and C++ differ in the type of the string literal. In C the type is array of char and in C++ it is constant array of char. In any case, you are not allowed to change the characters of the string literal, so the const in C++ is not really a restriction
but more of a type safety thing. A conversion from const char* to char* is generally not possible without an explicit cast for safety reasons. But for backwards compatibility with C the language C++ still allows assigning a string literal to a char* and gives
you a warning about this conversion being deprecated.



简单来说,是因为C++不同于C,C++里面的string是const的char数组,上面的C++代码,右边是一个string,把它赋值给了左边的char数组,所以编译器会报这个警告,注意如果试图对ss数组进行某一位修改:

ss[0] = 'H';
我试了下用这句代码修改ss数组某一位,编译可以通过,但是运行会崩溃,因为ss[0]指向const string的第一个元素,而任意试图对const string进行修改的操作都是错误的。

但是,如果重新赋值一个const string给ss,确是可以的:

ss = "Hello";
因为这样就相当于新建了一个"Hello"的const string,然后把它的地址复制给ss,也就相当于ss这个指针指向的内存发生了变化而已,并非试图修改原来"2cc5"的const string.

总之,既然都这样提醒了,就别这样干就行了,把char*定义为const的就行了:

const char *ss = "2cc5";
如此一来,代码中试图修改ss的某一位,编译就会报错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐