【发布时间】:2019-09-01 06:29:35
【问题描述】:
我已经尝试学习 C++ 大约一个月了,但它仍然让我感到困惑。例如这个“简单”的代码:
class A
{
int m;
public:
A() = default;
int getM() { return m; }
};
class B
{
int m;
public:
// empty body and empty initializer list
B() {} // isn't this the same as "B() = default;" ?
int getM() { return m; }
};
int main()
{
A a1;
A a2{};
std::cout << "a1.m=" << a1.getM() << "\n";
std::cout << "a2.m=" << a2.getM() << "\n";
B b1;
B b2{};
std::cout << "b1.m=" << b1.getM() << "\n";
std::cout << "b2.m=" << b2.getM() << "\n";
std::cin.ignore();
}
结果:
a1.m=...garbage
a2.m=0
b1.m=...garbage
b2.m=...garbage
根据CPP REFERENCE 编译器定义的默认构造函数确实有空的主体和空的初始化列表。因此,当显式定义具有空主体和空初始化程序列表的默认构造函数时,它是如何(在 A 类中)将成员“m”初始化为零的。根据 cppreference 摘录:
If the implicitly-declared default constructor is not defined as deleted, it is defined (that is, a function body is generated and compiled)
by the compiler if odr-used, and it has exactly the same effect as a user-defined constructor with empty body and empty initializer list.
据我了解,两个构造函数的行为方式应该完全相同。看起来很简单,但我不明白。
【问题讨论】:
-
我认为
A a2{};正在进行成员初始化。 -
@user4581301 必须是 C++11 或更高版本,否则
A a2{};和B b2{};无法编译,C++98/03 只接受A a2 = {}的形式。你应该把它作为答案。 -
我还是不明白 - cppreference 明确表示默认构造函数是空的,它的初始化列表也是空的 - 那么如果编译器提供的构造函数为空且为空,该成员如何初始化为零初始化列表?
-
重复的Is it guaranteed that defaulted constructor initialize built in types automatically to 0? 很接近,但不是很好的重复。两者都利用了Zero initialization,但骗子没有解释问题的关键:为什么
A有效而B无效。我已取消保留。 -
好的,大家:
A不是聚合(因为A::m是私有的),所以不能聚合初始化。
标签: c++ c++11 constructor initialization