What is std::string::c_str() lifetime?

ereOn picture ereOn · Jun 23, 2011 · Viewed 28.6k times · Source

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 ?

Thank you.

Answer

Kristopher Johnson picture Kristopher Johnson · Jun 23, 2011

The c_str() result becomes invalid if the std::string is destroyed or if a non-const member function of the string is called. So, usually you will want to make a copy of it if you need to keep it around.

In the case of your example, it appears that the results of c_str() are used safely, because the strings are not modified while in that scope. (However, we don't know what use_foo() or ~Foo() might be doing with those values; if they copy the strings elsewhere, then they should do a true copy, and not just copy the char pointers.)