In one of my programs, I have to interface with some legacy code that works with const char*
.
Lets say I have a structure which looks like:
struct Foo
{
const char* server;
const char* name;
};
My higher-level application only deals with std::string
, so I thought of using std::string::c_str()
to get back const char*
pointers.
But what is the lifetime of c_str()
?
Can I do something like this without facing undefined behavior?
{
std::string server = "my_server";
std::string name = "my_name";
Foo foo;
foo.server = server.c_str();
foo.name = name.c_str();
// We use foo
use_foo(foo);
// Foo is about to be destroyed, before name and server
}
Or am I supposed to immediately copy the result of c_str()
to another place?
.c_str()
. I didn't understand why sometimes I get only parts of the string, until I understood that theconst char*
does not live forever, but until the string is destroyed – Freese