C ++ returning temporary confusion objects

I have a fairly simple question in C ++, consider a function that takes some input parameters and creates std::string , which is from those parameters that are listed 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 goes out of scope when the function returns, but doesn’t also make this invalid for the constructed string?

What happens if I change the return type to const char * and return ss.str().c_str() instead?

Code like the one above seems to work, but I suspect that it was only because the memory containing the β€œtemporary” object was not overwritten by something else when I use it?

I must admit that I am rather confused in such situations as a whole, I would be grateful if someone could explain all these "temporary objects" - everything for me (or just point me in the right direction).

thanks in advance

+7
source share
3 answers

You return a temporary object, but since you return it by value, a copy is created. If you return a pointer or a link to a temporary object, this will be an error.

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

+10
source

As you can see Stringstream :: str () returns a std::string object. You return std::string without a reference, which means that without an optimization copy constructor, RVO (NRVO) will call and create a valid std::string object. During optimization, std::string will be moved without a copy constructor. But if std::string& returns, it will work, because this object will be destroyed after the function returns. The same effect will happen with const char * , because after destruction, this pointer will point to bad memory, and this is a dangerous situation.

+2
source

Suppose the following: T val = some_function() when you return a value from some_function C ++ copy the value of the return value to val using the specified copy constructor or built-in operator. Therefore, if you return int or std::string , there is no problem, but if you return a pointer to the memory to be freed at the end of the function, oops !! your pointer will point to invalid memory. For example, consider the following:

 const char* some_function() { std::string res( ... ); //... return res.c_str(); } 

You return a pointer to the data that will be released immediately after the function returns (since res will be destroyed and it will free its internal data) so that you get the address, but this address does not indicate what you might expect!

+1
source

All Articles