Search code examples
c++temporary-objects

C++ returning temporary objects confusion


I have a rather basic C++ question: Consider a function that takes some input parameters and creates a std::string from those parameters like the one below:

std::string constructString( int some_parameter ) {
    
    std::stringstream ss;
    
    // Construct a string (arbitrarily complex)
    ss << "Some parameter is " << some_parameter << " right now";

    return ss.str();    //Am I not returning a temporary object here?
}

I understand that the stringstream object will go out of scope when the function returns, but doesn't that invalidate the constructed string as well?

What would happen if I changed the return type to const char * and returned ss.str().c_str() instead?

Code like the above seems to work, but I suspect that's just because the memory containing the 'temporary' object has not yet been overwritten with something else when I use it?

I have to admit, I'm rather confused in such situations in general; I'd appreciate it if someone could explain this whole "temporary objects" thing to me (or just point me in the right direction).


Solution

  • You are returning a temporary object, but because you return it by value, the copy is created. If you return pointer or reference to temporary object, that would be a mistake.

    If you change the return type to const char * and return ss.str().c_str() you would return pointer to some buffer of temporary std::string returned by ss.str() and that would be bad.