Why can't I initialize an object incorporating itself into its initial value in c++?
c++, string, undefined-behavior
Solution
The C++11 standard has this to say about the scope of a newly declared name:
3.3.2 Point of declaration [basic.scope.pdecl]
The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:
int x = 12;
{ int x = x; }
Here the second x is initialized with its own (indeterminate) value. — end example ]
There is similar wording in prior C++ standards.
Off the top of my head, one rationale I can think of is that the name could be used in an initializer expression that takes the address of the object.
Problem
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.