The pointer returned by std::string::c_str() points to the memory supported by the string object. It remains valid until the function is called for the string object, or the string object is undermined. The string object you are worried about is temporary. It will be destroyed at the end of the full expression, not before or after. In your case, end the full expression after calling consumer so that your code is safe. This would not be so if the consumer saved the pointer somewhere, with the idea of โโusing it later.
The time series lifetime is strictly defined with C ++ 98. Before that, it varied depending on the compiler and the code you wrote would not work with g ++ (pre 1995, roughly - g ++ changed this almost immediately when the standards committee voted for it ) (Then there was no std::string , but the same problems affect any custom string class.)
James Kanze Apr 04 2018-12-12T00: 00Z
source share