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

标签 c++ constructor unions

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/

相关文章:

c++ - C++中实例变量的算法初始化

c - 在指向结构的指针上打印错误值

c++ - 变量总是在函数中重置为默认值

c++ - 什么是 diff b/w Includes in VC++ Directories options 和 Additional include directories in C++ -> General in Visual Studio

c++ - 标准中关于 "virtual function call in base constructor"的部分在哪里

c++ - 在不缩小的情况下初始化初始化列表中的 union 成员

c++ - 在这种情况下,C++ 中的 union 做了什么?

c++ - VS2015中的wpath在哪里

reflection - Kotlin使用反射调用构造函数

c++ - std::vector、构造函数、对象