c++ - 具有独占继承构造函数的类的值初始化

标签 c++ c++11 value-initialization

根据 cppreference没有任何用户提供的构造函数的非 union 类类型将在构造之前被零初始化:

If T is an non-union class type without any user-provided constructors, then the object is zero-initialized and then the implicitly-declared default constructor is called (unless it's trivial)

我不确定在使用 c++11 继承的构造函数时会发生什么,因为引文明确提到了隐式声明默认构造函数。

给定以下示例:

#include <iostream>

struct A {
    int a;
    A() {}
    A(int i): a(i) {}
};

struct B: public A {
    using A::A;
};

int main() {
    B b { 5 };
    B* p = new (&b) B{ };
    std::cout << b.a << std::endl;
}

正确的输出是 0 还是 5?专门提供继承构造函数的类类型是否应该在值初始化 (B{ }) 之前进行零初始化?

最佳答案

正确答案是 0,因为 B 的默认构造函数是隐式声明的。

请注意,默认、复制和移动构造函数不会被继承;引用自 §12.9/3 [class.inhctor]

For each non-template constructor in the candidate set of inherited constructors other than a constructor having no parameters or a copy/move constructor having a single parameter, a constructor is implicitly declared with the same constructor characteristics unless there is a user-declared constructor with the same signature in the complete class where the using-declaration appears or the constructor would be a default, copy, or move constructor for that class.


您的示例类似于 N3797 中列出的示例,§12.9/6(为简洁起见进行了编辑)

struct B2 {
  B2(int = 13, int = 42);
};

struct D2 : B2 {
  using B2::B2;
};

The candidate set of inherited constructors in D2 for B2 is
B2(const B2&)
B2(B2&&)
B2(int = 13, int = 42)
B2(int = 13)
B2()

The set of constructors present in D2 is
D2(), implicitly-declared default constructor, not inherited
D2(const D2&), implicitly-declared copy constructor, not inherited
D2(D2&&), implicitly-declared move constructor, not inherited
D2(int, int), implicitly-declared inheriting constructor
D2(int), implicitly-declared inheriting constructor

在您的例子中,BA 的候选继承构造函数集是

A()
A(int)
A(const& A)
A(A&&)

B 中的构造函数是

B() implicitly declared, not inherited
B(int) implicitly declared, inherited
B(const& B) implicitly declared, not inherited
B(B&&) implicitly declared, not inherited

关于c++ - 具有独占继承构造函数的类的值初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20255173/

相关文章:

c++ - 如何调用 clang++ 或 g++ 来准确复制两个不同标准版本中的需求

c++ - vector 容器和 unique_ptr

c++ - 在 C++ 代码中使用/混合 C?

c++ - 从 GCC 4.6 更改为 4.7 时 undefined reference

c++ - 用作初始值设定项时,空括号 (“T()” ) 和空大括号 (“T{}” ) 有什么区别吗?

c++ - 原始数据类型在循环内分配了多少次?

C++ Linux : Get the refresh rate of a monitor

python - 从文件中提取与另一个文件中的条件匹配的某些行

c++ - 针对 Visual Studio 2008 的 C++11 代码的兼容性

c++ - 左移一个特定的编号。的 1s 具体编号次