根据 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
forB2
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
在您的例子中,B
中 A
的候选继承构造函数集是
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/