Std :: string :: c_str () and temporary

Is the following C ++ code correct:

void consumer(char const* p) { std::printf("%s", p); } std::string random_string_generator() { // returns a random std::string object } consumer(random_string_generator().c_str()); 

The problem with this is that after creating a temporary std :: string object and accepting the c_str () pointer, nothing prevents the destruction of the std :: string object (or maybe I'm wrong?). Could you please tell me the standard if the code is ok, despite everything. It works when I test g ++.

+45
c ++ stdstring stl
Apr 04 2018-12-12T00:
source share
3 answers

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.)

+55
Apr 04 2018-12-12T00:
source share
โ€” -

The temporary lifetime of std::string extends only beyond where consumer returns, so you can safely use anything on this line directly from consumer . What's wrong is to save the value returned by c_str and try to use it later (the temporary one will be destroyed, and we can only guess what you will find on the other end of the pointer).

+17
Apr 04 2018-12-12T00:
source share

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

+5
Apr 04 2018-12-12T00:
source share



All Articles