[ACCEPTED]-std::string::c_str() and temporaries-stdstring

Accepted answer
Score: 85

The pointer returned by std::string::c_str() points to memory 19 maintained by the string object. It remains 18 valid until a non-const function is called 17 on the string object, or the string object 16 is destructed. The string object you're 15 concerned about is a temporary. It will 14 be destructed at the end of the full expression, not 13 before and not after. In your case, the 12 end of the full expression is after the call 11 to consumer, so your code is safe. It wouldn't 10 be if consumer saved the pointer somewhere, with 9 the idea of using it later.

The lifetime 8 of temporaries has been strictly defined 7 since C++98. Before that, it varied, depending 6 on the compiler, and the code you've written 5 wouldn't have worked with g++ (pre 1995, roughly—g++ changed 4 this almost immediately when the standards 3 committee voted it). (There wasn't an std::string then 2 either, but the same issues affect any user 1 written string class.)

Score: 23

The temporary std::string's lifetime extends just beyond 7 the point where consumer returns, so it is safe 6 to use anything on that string directly from within consumer. What is 5 not OK is to store the value that c_str returns 4 and try to use it later (the temporary will 3 have been destroyed, and we can only guess 2 what you will find at the other end of the 1 pointer).

Score: 5

The temporary returned by the function random_string_generator() can 1 be used in consumer() function safely.

More Related questions