Lifetime of std::string::c_str() Result
Question:
In a program interfacing with legacy code that uses const char pointers, a developer queries about the lifetime of std::string::c_str() results. They specifically ask if the following code snippet is safe:
{ std::string server = "my_server"; std::string name = "my_name"; Foo foo; foo.server = server.c_str(); foo.name = name.c_str(); // use Foo // Foo about to be destroyed (before name and server) }
Answer:
The lifetime of std::string::c_str() results depends on the string's lifetime and any subsequent modifications. The result becomes invalid if the string is modified or destroyed. Therefore, making a copy of the result is generally recommended when intending to store it for future use.
In the provided code snippet, the std::strings (server and name) are created and modified within the scope of the code block. The c_str() results (foo.server and foo.name) point to these temporary std::strings, which are destroyed at the end of the scope.
However, the strings are not used outside of the scope, making it technically safe to continue using the const char pointers in use_foo() and ~Foo(). However, if these functions potentially copy the pointers to other locations, true copies should be made instead of simply copying the pointers.
Therefore, while the code snippet demonstrates technically correct behavior in this specific case, good coding practice would involve making copies of the c_str() results if they need to be stored for later use.
The above is the detailed content of How Long Do `std::string::c_str()` Pointers Remain Valid?. For more information, please follow other related articles on the PHP Chinese website!