是类型名称=名称;在 C++ 中有用过吗?

发布于 2024-11-27 19:19:51 字数 184 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

叹沉浮 2024-12-04 19:19:52

有时,如果您有复杂的初始化程序,那么您可能必须引用它。这在构造函数中使用,您可以在初始化列表中传递对 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.

多孤肩上扛 2024-12-04 19:19:52

这是有效的,但几乎不言而喻,这

int a = a;

比没有更有害。

至于其他类型,我想说,可以通过重载复制构造函数并使用默认构造来完成有用的工作。

另一方面,我想不出任何需要此类代码的情况,并且由于在我看来,这种语法使代码变得如此复杂,所以我的主观意见是,这并不是能够编写此类作业的任何充分理由。尤其是当人们考虑到可以通过禁止(或至少警告)该语法来防止所有错误时。

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.

饭团 2024-12-04 19:19:52

这样的代码永远不会有用,这会导致不确定性。

第一种情况是未定义的行为(使用未初始化的自身进行初始化),第二种情况也是未定义的行为(在未初始化的对象上调用复制构造函数)。永远不应该练习它。

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.

梦晓ヶ微光ヅ倾城 2024-12-04 19:19:51

这让我想起了旧的GCC 邮件列表的线程 Gabriel Dos Reis给出了以下构造单节点循环链表的例子:

struct Node {
  Node* link;
  Node(Node& n) : link(&n) { }
};

int main()
{
  Node x = x;
}

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;
}
蒗幽 2024-12-04 19:19:51

您可以在其初始值设定项中使用变量的名称。该代码

Type name = name;

可能没有用,但代码

Type name = f(&name);

可能有用。

在很多地方,语言语法并不禁止无用的构造。 :-)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文