gpt4 book ai didi

c++ - 如果只有一个成员没有默认构造函数,为什么 union 有一个已删除的默认构造函数?

转载 作者:IT老高 更新时间:2023-10-28 23:19:23 26 4
gpt4 key购买 nike

N3797::9.5/2 [class.union] 说:

If any non-static data member of a union has a non-trivial default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8), or destructor (12.4), the corresponding member function of the union must be user-provided or it will be implicitly deleted (8.4.3) for the union

我试图通过示例来理解该注释:

#include <iostream>
#include <limits>

struct A
{
A(const A&){ std::cout << "~A()" << std::endl; } //A has no default constructor
};

union U
{
A a;
};

U u; //error: call to implicitly-deleted default constructor of 'U'

int main()
{

}

DEMO

我不太清楚这种行为。 struct A 没有隐式声明的默认构造函数,因为 12.1/4: [class.ctor] 说:

If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).

这意味着 struct A 没有非平凡的默认构造函数(根本没有默认构造函数,特别是非平凡的)。那就是 union U 不必删除默认构造函数。怎么了?

最佳答案

相关措辞在 C++11 [class.ctor]p5 中(重点是我的):

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4). [...] A defaulted default constructor for class X is defined as deleted if:

[...]

  • X is a union-like class that has a variant member with a non-trivial default constructor,

[...]

  • any direct or virtual base class, or non-static data member with no brace-or-equal-initializer, has class type M (or array thereof) and either M has no default constructor or overload resolution (13.3) as applied to M's default constructor results in an ambiguity or in a function that is deleted or inaccessible from the defaulted default constructor, or

[...]

您的类 A 没有默认构造函数,因此类 X(无论是 union 还是非 union )的默认默认构造函数(无论是隐式还是显式)包含A 类型的非静态数据成员没有初始化程序会导致 X 的默认构造函数被删除。它必须:编译器根本无法生成任何其他默认构造函数。

至于你在评论中的后续问题:

如果 A not 有一个非平凡的默认构造函数而不是 A not,那么在 union 和非 union 类,这也是 [class.ctor]p5 的一部分:这是我在之前的引文中没有强调的第一个要点。

关于c++ - 如果只有一个成员没有默认构造函数,为什么 union 有一个已删除的默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26572240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com