C++ deprecated conversion from string constant to

2018-12-31 19:58发布

I have a class with a private char str[256];

and for it I have an explicit constructor:

explicit myClass(const char *func)
{
    strcpy(str,func);
}

I call it as:

myClass obj("example");

When I compile this I get the following warning:

deprecated conversion from string constant to 'char*'

Why is this happening?

11条回答
梦该遗忘
2楼-- · 2018-12-31 20:27

In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.

查看更多
听够珍惜
3楼-- · 2018-12-31 20:32

I solve this problem by adding this macro in the beginning of the code, somewhere. Or add it in <iostream>, hehe.

 #define C_TEXT( text ) ((char*)std::string( text ).c_str())
查看更多
琉璃瓶的回忆
4楼-- · 2018-12-31 20:36

I also got the same problem. And what I simple did is just adding const char* instead of char*. And the problem solved. As others have mentioned above it is a compatible error. C treats strings as char arrays while C++ treat them as const char arrays.

查看更多
与君花间醉酒
5楼-- · 2018-12-31 20:41

The warning:

deprecated conversion from string constant to 'char*'

is given because you are doing somewhere (not in the code you posted) something like:

void foo(char* str);
foo("hello");

The problem is that you are trying to convert a string literal (with type const char[]) to char*.

You can convert a const char[] to const char* because the array decays to the pointer, but what you are doing is making a mutable a constant.

This conversion is probably allowed for C compatibility and just gives you the warning mentioned.

查看更多
听够珍惜
6楼-- · 2018-12-31 20:41

The following illustrates the solution, assign your string to a variable pointer to a constant array of char (a string is a constant pointer to a constant array of char - plus length info):

#include <iostream>

void Swap(const char * & left, const char * & right) {
    const char *const temp = left;
    left = right;
    right = temp;
}

int main() {
    const char * x = "Hello"; // These works because you are making a variable
    const char * y = "World"; // pointer to a constant string
    std::cout << "x = " << x << ", y = " << y << '\n';
    Swap(x, y);
    std::cout << "x = " << x << ", y = " << y << '\n';
}
查看更多
何处买醉
7楼-- · 2018-12-31 20:43

Maybe you can try this:

void foo(const char* str) 
{
    // Do something
}

foo("Hello")

It works for me

查看更多
登录 后发表回答