默认初始化显式构造函数 c++

发布于 2025-01-09 12:00:50 字数 436 浏览 4 评论 0原文

如果默认构造函数是显式的,那么 C++11 中的默认初始化如何工作?例如:

#include <iostream>

struct Foo {
  int x;

  explicit Foo(int y = 7) : x{y} {}
}

int main() {
  Foo foo;
  std::cout << foo.x << std::endl;
}

在main中,变量foo被默认初始化。根据我的理解,这将调用默认构造函数(如果存在)。否则,不会发生初始化,foo 包含不确定的值,并且打印 foo.x 是未定义的行为。

Foo 有一个默认构造函数,但它是显式的。该构造函数是否保证被调用,或者程序的最后一行是未定义的行为?

How does default initialization work in C++11 if the default constructor is explicit? For example:

#include <iostream>

struct Foo {
  int x;

  explicit Foo(int y = 7) : x{y} {}
}

int main() {
  Foo foo;
  std::cout << foo.x << std::endl;
}

In main, the variable foo is default initialized. Based on my understanding, this will call a default constructor, if one exists. Otherwise, no initialization occurs, foo contains indeterminate values, and printing foo.x is undefined behavior.

There is a default constructor for Foo, but it is explicit. Is that constructor guaranteed to be called, or is the last line of the program undefined behavior?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

荒岛晴空 2025-01-16 12:00:50

你的使用没问题。可能发生的最糟糕的事情是编译器将无法使用构造函数,因为它是显式的并且无法编译。但是,定义一个变量将正确调用显式默认构造函数。

对默认构造函数使用显式可以防止如下使用:

Foo some_fn() {
  return {}; // Fails as the default constructor is explicit.
  return Foo{}; // OK
}

Your use is okay. The worst thing that could happen would be that the compiler would not be able to use the constructor since it is explicit and fail to compile. However, defining a variable as you have will correctly call the explicit default constructor.

The use of explicit for a default constructor prevents uses like the following:

Foo some_fn() {
  return {}; // Fails as the default constructor is explicit.
  return Foo{}; // OK
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文