Search code examples
c++temporary

Passing a temporary object to std::cout


I have this very simple piece of testing code:

std::string a = "A"
std::string b = "B"

std::cout << a + b << std::endl;

While it works in GNU g++, I'm worried if it is portable to pass the temporary a + b to std::cout, as in, is std::cout guaranteed to receive the correct piece of memory?

Many thanks!


Solution

  • It's safe. The temporary will not be destroyed until it has been processed by cout.

    For more details, see When are temporaries created as part of a function call destroyed?