Short Answer:
const char *get_string() { return ""; }
or
char *get_string() { return const_cast<char *>(""); }
or
char *get_string() { return NULL; }
or
std::string get_string() { return std::string(); }
Detailed Answer:
Implicit conversion from string literal to char *
is supported in C and C++98/C++03, but apparently not in C++11. The deprecation warning is just there to let you know that this should be addressed, particularly if you want to be able to migrate your code C++11.
The empty string literal ("") is not actually empty, it is a string containing a single null character (\0). When you use return "";
, you are actually returning a pointer to the memory location of the const string literal so the function return type should be const char *
.
If you really must return a non-const pointer to a string literal, you can use the const_cast
operator to cast away the const
.
A better practice would be to return NULL (or nullptr
) for functions that are returning empty, non-const, C-style strings, but only if the calling code is checking for NULL pointers.
Note that C++ has its own string type (std::string
), and an even better practice would be to use this rather than a C-style string when possible.