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

来源:互联网 发布:淘宝宝贝详情图尺寸 编辑:程序博客网 时间:2024/06/08 01:20

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的某一位,编译就会报错。



0 0
原创粉丝点击