I was debugging a program when I came across the following code I had erroneously typed similar to the following:
//Original (wrong)
std::string first("Hello");
std::string second = first + second;
//Instead of this (correct)
std::string first("Hello");
std::string second = first + something_else;
Obviously I wasn't trying to do this (I can't think why anyone would want to do this), but it got me thinking. It doesn't look like the original should work, and I would assume it is undefined. Indeed, this was the source of my problem.
To make the problem more general, consider the following:
SomeType a;
SomeType b = a + b;
Is the behavior undefined simply because b
is not yet initialized (see this answer)?
If the behavior is undefined, then my real question is, why?
Is this only undefined for certain standard containers, like std::string
, or is this undefined in a more general sense (STL classes, user-defined classes, PODs, fundamental types)?
What part of the standard applies to this?
Assume this is c++11, if necessary.