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.
David thornley
source share