开发者

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

开发者 https://www.devze.com 2023-03-24 01:47 出处:网络
The following code is allowed in C++: int a = a; or Type name = name; Both lead to an uninitialized object being initialized by i开发者_JAVA百科tself, which often leads to undefined behavior.

The following code is allowed in C++:

int a = a;

or

Type name = name;

Both lead to an uninitialized object being initialized by i开发者_JAVA百科tself, which often leads to undefined behavior.

Is such code ever needed or reasonable? Are there cases of such code being useful?


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消