Hello.
I have an instance of std::string, but I need to pass it's contents to a function taking char* as the argument. Now I know that string::c_str() returns a const char*, but the function wants it to be a non-const character array. What would be the best way of converting the return value of string::c_str() to a pointer pointing to a non-const char array?
Is a simple const_cast sufficient? Is it really safe? I think the function wants to modify the string (otherwise it would take a const char*, right?) Can an instance of std::string be modified (after doing const_cast) through the pointer returned by string::c_str()?
If const_casting isn't safe, what would be the best alternative?
Comments
[italic]Is a simple const_cast sufficient? Is it really safe? [/italic]
That's the whole point of [b]const_cast[/b]. It's used to cast-away or add [b]const[/b] type modifier.
[italic]
I think the function wants to modify the string (otherwise it would take a const char*, right?)[/italic]
I'm not sure about that. If this function is in the standard library then it's probably true. Otherwise it's possible that the function requests a [b]char*[/b] but does not modify the string.
[italic]Can an instance of std::string be modified (after doing const_cast) through the pointer returned by string::c_str()?[/italic]
I don't think that's a good idea. You can't be sure how the string is represented inside the [b]std::string[/b] container.
[italic]If const_casting isn't safe, what would be the best alternative?[/italic]
Use [b]std::string::copy()[/b] to copy the contents into a character array then pass this array to the function. If you are [italic]absolutely sure[/italic] that the function doesn't modify the string than you can use [b]const_cast[/b].
: alternative?[/italic]
: Use [b]std::string::copy()[/b] to copy the contents into a character
: array then pass this array to the function. If you are
: [italic]absolutely sure[/italic] that the function doesn't modify
: the string than you can use [b]const_cast[/b].
Thanks! That was the point of my question: I do not know what the function does with the pointer as I don't have a (source code) access to the function. Therefore I'm going to go with the string::copy() and just remember to add " " at the end of the returned array. Then the function can do what ever it pleases with the string.
Or you can use strcpy(dest, str.c_str()) which copies the trailing .