Is Type name = name; ever useful in C++?

2020-08-10 07:53发布

问题:

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?

回答1:

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. :-)



回答2:

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;
}


回答3:

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.



回答4:

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.



回答5:

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.