std::string::c_str()
gives you the pointer to the internal buffer of the
std::string object. This pointer will be valid
only as long the
std::string object still exists
and if
no modifications are made to the string object.
Hence, getting the pointer to an
empty (default-constructed) string object isn't really helpful.
You could just as well write:
const char* in_buffer = ""; // ...instead of: empty_string.c_str();
If, later, you plan to append something to the
std::string object, it is likely that the internal buffer will be re-allocated and therefore the pointer that you received earlier is
invalidated! So, this would be a
bad idea:
1 2 3 4
|
std::string str0;
const char* buffer = str0.c_str();
str0 += "hello world!";
do_something_with(buffer); // <-- pointer 'buffer' is probably invalid at this point!
|
But why do you even need a "raw" pointer? Can't you pass, e.g., a
const reference to
std::string
object?
1 2 3 4 5 6 7 8 9 10
|
void do_something_with(const std::string &string_ref)
{
/* ... */
}
int main()
{
std::string client_name = std::string("client") + std::to_string(getpid());
do_something_with(client_name);
}
|