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!

有帮助吗?

解决方案

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?

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top