Is it safe to call methods of temporary objects?

I have a function that should return char *. Since I have to concatenate some lines, I wrote the following line:

std::string other_text; // ... func(("text" + other_text).c_str()); 

I know that I could avoid the question calling the line I want to use. I just want to take the opportunity to ask a more general question: is it safe to call temporary variable methods? Does this match standard?

+7
c ++ string stl g ++
source share
4 answers

It is safe to call temporary variable methods, but it is not safe to return a char * temporary variable for later use.

This char * indicates a buffer that will be freed soon. Once it is released, you will have a pointer to an invalid region in memory.

Instead, return the std :: string object.

+12
source share

You are allowed to call methods in temporary mode, but you must be careful about the lifetime of the object — in particular, if you have a function that returns c_str() called in the temporary std::string , this string object will be destroyed when the function returns .

Your code above suffers from this problem.

+6
source share

The C string returned by calling c_str () in a temporary action will be valid until the next call to c_str () on a temporary action, which will never happen. The temporary itself hangs until the end of the full expression, this is the part (return statement).

If you return std :: string, everything will be hunkydory, as the string copy constructor will be called in the return to take the copy. If you return char *, then all bets will be disabled, since the value you return will be deleted when the function exits. This has nothing to do with the temporary one, this is a common problem when returning char * - instead return std :: string.

+4
source share

The generated pointer will be useful as long as the temporary object is still around, which is usually until the end of the expression. Exceptions are temporary use in the initializer (in this case, it continues until the initialization is completed) or when binding to a link. The temporary expression in the returned function continues until the function exits (if it is not bound to a link). Once the temporary time of life is over, the temporary is destroyed. In this case, this means that the string destructor is executed, and therefore, the memory for characters is freed. In other words, upon returning the value, it would guarantee invalidity.

You can pass a string directly by returning it as a reference to a constant. You can copy .c_str () to the new allocated memory and pass it back (as a pointer or smart pointer). Any of them will work.

The lifetime of temporary objects is described in section 12.2 of the C ++ standard. According to the standard, you return a pointer to freed memory.

+1
source share

All Articles