Is it Safe to Access the c_str() of a Temporary String?
In a C program, the following code raises a concern:
void consumer(char const* p) { std::printf("%s", p); } std::string random_string_generator(); consumer(random_string_generator().c_str());
It is contended that the temporary std::string object generated by random_string_generator may be destroyed before the call to consumer, potentially rendering the c_str() pointer invalid. However, it is crucial to understand the standard's definition of временной переменных lifetime.
According to the C Standard, the pointer returned by std::string::c_str() remains valid until a non-const function is invoked on the std::string object or it is destructed. In the given code, the temporary std::string object will be destructed at the end of the full expression, which includes the call to consumer. This confirms that the code is well-formed.
As long as consumer does not attempt to preserve the c_str() pointer for later usage, it is safe to assume that the temporary std::string object will not be destructed prematurely. The lifetime of temporaries has been precisely defined since C 98, ensuring that code such as the one presented will execute safely across different compilers.
The above is the detailed content of Is It Safe to Access the `c_str()` of a Temporary `std::string` Object?. For more information, please follow other related articles on the PHP Chinese website!