zoukankan      html  css  js  c++  java
  • [Warning] deprecated conversion from string constant to 'char*' 原因

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



  • 相关阅读:
    新版《星光大道》
    acl 3.1.2版本发布,网络通信与服务器编程框架
    批量将 *.c 预处理为 *.i (递归处理文件夹中所有文件)gcc -E
    texmaker——unknown graphics extension .eps
    TexMaker
    中国计算机学会推荐国际学术会议和期刊目录
    浅谈阶梯博弈
    【hdu 3389】Game
    【hdu 3537】Daizhenyang's Coin
    【hdu 3863】No Gambling
  • 原文地址:https://www.cnblogs.com/lvlang/p/10586370.html
Copyright © 2011-2022 走看看