The following code is allowed in C++:
int a = a;
or
Type name = name;
Both lead to an uninitialized object being initialized by itself, which often leads to undefined behavior.
Is such code ever needed or reasonable? Are there cases of such code being useful?
You are allowed to use the name of the variable in its initializer. The code
Type name = name;
is probably not useful, but the code
Type name = f(&name);
might be.
There are many places where the language syntax doesn't forbid useless constructs. :-)
This reminded me of an old thread of the GCC mailing list in which Gabriel Dos Reis gave the following example to construct a one-node circular list:
struct Node {
Node* link;
Node(Node& n) : link(&n) { }
};
int main()
{
Node x = x;
}
Sometimes, if you have complex initializers, then you can have to refer to it. This is used in constructors where you pass pointer or references to this
in the initialization list.
It is valid, but it almost goes without saying that
int a = a;
is more harmful than not.
As for other types I would say, that one might do useful work by overloading the copy constructor and using default construction.
On the other hand I cannot think of any circumstance where such code is needed, and since IMO the code gets so convoluted by this syntax, my subjective opinion is that it isn't any good reason to be able to write such assignments. Especially not when one consider all the bugs that could be prevented by disallowing (or at least warn about) the syntax.
Such code can never be useful which leads uncertainty.
First case is undefined behavior (initializing with uninitialized self) and 2nd case is also an undefined behavior (copy constructor is called on uninitialized object). It should never be practiced.