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



  • 相关阅读:
    metasploit(MSF)对windows的ms17-010漏洞利用
    kali 解决Metasploit拿到shell后显示中文乱码问题
    kali安装搜狗输入法
    Struts2 为Action 的属性注入值&& 处理请求后缀
    Action 名称搜索顺序&Action配置中的各项默认值
    Struts.xml配置中的包介绍
    AJAX 使用XMLHttpRequest对象发送和接受数据
    Unicode 汉字编码
    HTTP 协议 请求头详解
    java Dom 解析 XML 详细解答
  • 原文地址:https://www.cnblogs.com/lvlang/p/10586370.html
Copyright © 2011-2022 走看看