C++警告:不推荐将字符串常量转换为'char*'[-Wwrite-strings]

Sag*_*gar 22 c++ string-literals

我正在使用gnuplot在C++中绘制图形.该图正如预期的那样绘制,但在编译期间会出现警告.警告意味着什么?

warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的功能:

void plotgraph(double xvals[],double yvals[], int NUM_POINTS)
{
    char * commandsForGnuplot[] = {"set title \"Probability Graph\"", 
        "plot     'data.temp' with lines"};
    FILE * temp = fopen("data.temp", "w");
    FILE * gnuplotPipe = popen ("gnuplot -persistent ", "w");
    int i;
    for (i=0; i < NUM_POINTS; i++)
    {
        fprintf(temp, "%lf %lf \n", xvals[i], yvals[i]); 
        //Write the data to a te  mporary file
    }
    for (i=0; i < NUM_COMMANDS; i++)
    {
        fprintf(gnuplotPipe, "%s \n", commandsForGnuplot[i]); 
        //Send commands to gn  uplot one by one.
    }
    fflush(gnuplotPipe);
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*our 35

字符串文字是一个const char数组,我们可以从草案C++标准部分2.14.5 字符串文字中看出这一点(强调我的):

普通字符串文字和UTF-8字符串文字也称为窄字符串文字.窄字符串文字的类型为"n const char数组",其中n是下面定义的字符串大小,并且具有静态存储持续时间(3.7).

所以这个改变将删除警告:

const char * commandsForGnuplot[] = {"set title \"Probability Graph\"", "plot     'data.temp' with lines"};
^^^^^
Run Code Online (Sandbox Code Playgroud)

注意,允许*非const char**指向const数据是一个坏主意,因为修改const字符串文字未定义的行为.我们可以通过转到7.1.6.1 cv-qualifiers部分看到这一点:

除了可以修改声明为mutable(7.1.1)的任何类成员之外,任何在其生命周期内修改const对象的尝试(3.8)都会导致未定义的行为.

和部分2.14.5 字符串文字说:

是否所有字符串文字都是不同的(即存储在非重叠对象中)是实现定义的.尝试修改字符串文字的效果是未定义的.