[英]C++ warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
I am using gnuplot to draw a graph in C++. 我正在使用gnuplot在C ++中绘制图形。 The graph is being plot as expected but there is a warning during compilation.
该图形正在按预期方式绘制,但是在编译过程中会出现警告。 What does the warning mean?
警告是什么意思?
warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
This is the function I am using: 这是我正在使用的功能:
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);
}
String literals are an array of const char , we can see this from the draft C++ standard section 2.14.5
String literals which says ( emphasis mine ): 字符串文字是const char的数组 ,我们可以从C ++标准草案
2.14.5
字符串文字中看到这一点, 字符串文字 ( 强调我的意思 ):
Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals.
普通字符串文字和UTF-8字符串文字也称为窄字符串文字。 A narrow string literal has type “array of n const char” , where n is the size of the string as defined below, and has static storage duration (3.7).
窄字符串文字的类型为“ n of const char数组” ,其中n是下面定义的字符串的大小,并且具有静态存储持续时间(3.7)。
so this change will remove the warning: 因此此更改将删除警告:
const char * commandsForGnuplot[] = {"set title \"Probability Graph\"", "plot 'data.temp' with lines"};
^^^^^
Note, allowing a *non-const char** to point to const data is a bad idea since modifying a const or a string literal is undefined behavior . 注意,允许* non-const char **指向const数据是一个坏主意,因为修改const或字符串文字是未定义的行为 。 We can see this by going to section
7.1.6.1
The cv-qualifiers which says: 我们可以通过第
7.1.6.1
节cv-qualifiers看到这一点:
Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.
除了可以声明任何声明为可变的类成员(7.1.1)之外,任何在其生存期(3.8)内修改const对象的尝试都会导致未定义的行为。
and section 2.14.5
String literals which says: 和第
2.14.5
节“ 字符串文字”指出:
Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined.
是否定义了所有字符串文字(即存储在不重叠的对象中)都是实现定义的。 The effect of attempting to modify a string literal is undefined.
尝试修改字符串文字的效果是不确定的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.