是类型名称=名称;在 C++ 中有用过吗?
C++ 中允许使用以下代码:
int a = a;
或
Type name = name;
两者都会导致未初始化的对象自行初始化,这通常会导致未定义的行为。
这样的代码是否需要或合理?此类代码是否有用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
有时,如果您有复杂的初始化程序,那么您可能必须引用它。这在构造函数中使用,您可以在初始化列表中传递对
this
的指针或引用。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
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.
这让我想起了旧的GCC 邮件列表的线程 Gabriel Dos Reis给出了以下构造单节点循环链表的例子:
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:
您可以在其初始值设定项中使用变量的名称。该代码
可能没有用,但代码
可能有用。
在很多地方,语言语法并不禁止无用的构造。 :-)
You are allowed to use the name of the variable in its initializer. The code
is probably not useful, but the code
might be.
There are many places where the language syntax doesn't forbid useless constructs. :-)