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

2020-08-10 07:49发布

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?

5条回答
We Are One
2楼-- · 2020-08-10 08:07

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.

查看更多
冷血范
3楼-- · 2020-08-10 08:21

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.

查看更多
Explosion°爆炸
4楼-- · 2020-08-10 08:28

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;
}
查看更多
地球回转人心会变
5楼-- · 2020-08-10 08:30

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

查看更多
来,给爷笑一个
6楼-- · 2020-08-10 08:30

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.

查看更多
登录 后发表回答