c++ - 根据 C++11 标准中的 §12.1/4,代码不应编译

标签 c++ c++11 constructor language-lawyer

§12.1/4:及其第一个要点

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). An implicitly-declared default constructor is an inline public member of its class. 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,

根据这个要点,这个片段不应该编译,因为 struct A 是一个类似 union 的类(它包含一个匿名 union )并且它有一个变体成员,B b; 带有一个非平凡的默认构造函数。但是 code compiles without a problem in vc++, clang++ and g++ .

#include <iostream>

struct B { B(): i(10) {} int i; };

struct A
{
    union{ int y = 1; double x; };
    int i;
    A(int j) : i{j} {};
    B b;
    A() = default;
};

int main() {
    A a;
}

最佳答案

变体成员是

union{ int y = 1; double x; };

而且它们都没有非平凡的构造函数。

这在 §9.5/8 中定义:

9.5 Unions [class.union]

8 A union-like class is a union or a class that has an anonymous union as a direct member. A union-like class X has a set of variant members. If X is a union its variant members are the non-static data members; otherwise, its variant members are the non-static data members of all anonymous unions that are members of X.

关于c++ - 根据 C++11 标准中的 §12.1/4,代码不应编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093669/

相关文章:

c++ - win32 全选编辑 ctrl(文本框)

c++ - 具有不同返回类型的方法的类型删除

java - 不需要父构造函数的子类

Java,使用参数列表进行构造函数调用?

c++ - Visual Studio 2015 (C++) 代码大小

c++ - 与 MSVC 的链接错误,但与带有 constexpr 的 g++ 的链接错误

c++ - jGRASP c++ 安装问题找不到-lfeglut

c++ - 在 C++11 之后的现代 C++ 中使用原始指针

c++ - 防止将 uint64_t 转换为 uint16_t

c# - 功能(): this(null) {}