为什么默认的默认构造函数取决于它是在课堂内还是外部声明的?

发布于 2025-01-23 10:05:22 字数 774 浏览 1 评论 0原文

在下面的示例中,struct a没有默认的构造函数。因此,struct bstruct c从中继承的c 无法获得编译器生成的默认构造函数:

struct A {
    A(int) {}
};

struct B : A {
    B() = default; //#1
};

struct C : A {
    C();
};

C::C() = default; //#2

#1。 In struct B, defaulted default constructor is declared inside the class, and all compilers accept it, with only Clang showing a warning saying that explicitly defaulted default constructor is implicitly deleted [-Wdefaulted-function-删除]

#2。但是在struct C之外声明的默认默认构造函数生成了编译器错误。演示: https://gcc.godbolt.org/z/z/ z/3EGC4RTQE

构造函数被默认:课堂内还是外部?

In the following example, struct A does not have default constructor. So both struct B and struct C inherited from it cannot get compiler-generated default constructor:

struct A {
    A(int) {}
};

struct B : A {
    B() = default; //#1
};

struct C : A {
    C();
};

C::C() = default; //#2

#1. In struct B, defaulted default constructor is declared inside the class, and all compilers accept it, with only Clang showing a warning saying that explicitly defaulted default constructor is implicitly deleted [-Wdefaulted-function-deleted]

#2. But defaulted default constructor declared outside of struct C generates a compiler error. Demo: https://gcc.godbolt.org/z/3EGc4rTqE

Why does it matter where the constructor is defaulted: inside or outside the class?

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

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

发布评论

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

评论(1

临走之时 2025-01-30 10:05:22

请注意,如果您实际尝试并实例化b,那么您还会删除b :: b()的错误: https://gcc.godbolt.org/z/jdkzv7zvdd

差异的原因可能是当您声明c c c时,构造函数,c的用户(假设定义在另一个翻译单元中)无法知道构造函数实际上已删除。充其量,这会导致一些令人困惑的链接错误,最坏的情况是在运行时崩溃。在b的情况下clang)将其声明为违约。

Note that if you actually try and instantiate B then you'll also get the error that B::B() is deleted: https://gcc.godbolt.org/z/jdKzv7zvd

The reason for the difference is probably that when you declare the C constructor, the users of C (assuming the definition is in another translation unit) have no way of knowing that the constructor is in fact deleted. At best this would lead to some confusing linker error, at worst it'd just crash at runtime. In the case of B all users of B will immediately be able to tell that the default constructor is deleted so it does no harm (even if it makes no sense as warned by clang) to declare it as defaulted.

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