C++ returning temporary objects confusion

As you see Stringstream::str() returns std::string object. You returns std::string without reference that means that without RVO(NRVO) optimization copy constructor will call and create valid std::string object. With optimization std::string will be moved without copy constructor. But if will return std::string& it will crash because this object will be destroyed after function return. Same effect will be with const char * because after destroying this pointer will point on bad memory and this is dangerous situation.


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.