简体   繁体   中英

How can I fix warning deprecated conversion from string constant to 'char*' in C++?

The code is:

char *prefix(node)::name() const 
{ 
   return str(prefix(node)); 
}

The message is deprecated conversion from string constant to 'char*'

How can I solve it?

The reason you get this warning is that the pointer you return points to global data that may or may not be protected as read-only, so any change to it will either crash or be reflected on each subsequent call.

If you think that it's not an issue because you don't plan to modify it, return a const char* instead. If you want to return a locally-modifiable string (one on which changes won't be reflected on subsequent calls to this method), either return a std::string or strdup the string (but then don't forget to free it by yourself). If you want to return a globally-modifiable string (one where the changes will be reflected on subsequent calls to this method), return a pointer to a global array instead of a direct string constant:

char *prefix(node)::name() const 
{
    static char string[] = str(prefix(node));
    return string;
}

This assumes that str is a macro returning a string constant.

The latter solution implements a warning-less state of status quo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM