Question

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!

Était-ce utile?

La 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?

Autres conseils

Yes -- a+b creates a temporary std::string object, which gets passed to std::cout. At the end of the full expression in which it was created, that temporary object will be destroyed, but not before, so it'll remain valid until the end of the expression.

Other than that, the temporary is pretty much the same as almost any other std::string object, so the fact that it's a temporary object is irrelevant to how it's treated by std::cout.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top