Update: for the getValue function I have no control, so is there anything I can do from my side?
I have a kind of dumb question about string and char * basic.
I’m using a function that returns a char * value,
const char *getValue(const char *key)
{
//if key found, and valueString is a string
return valueString.c_str();
//else
return NULL;
}
then I initialized a string to hold the return value,
std::string value = getValue(key);
problem is, whenever the value is not found, which means the function returns NULL, my assignment line will run into an exception. But when there is a legal return value, everything is working fine.
I’m wondering
1. Is this usage totally wrong? means I should never mix char * with string?
2. If not, then when there is a legal pointer returned, does my string automatically make a copy and store it?
3. What is the best way to do this?
Thanks.
Since you have no control over what the
getValue()function does, you need to check the return value for NULL before assigning it to thestd::string.