[英]Does the defaulted default constructor initialize variables to zero?
I'm updating a class to C++14, and trying to figure out the simplest way to initialize all of the instance variables to zero on construction. 我正在将类更新为C ++ 14,并试图找出在构造时将所有实例变量初始化为零的最简单方法。 Here's what I have so far:
这是我到目前为止所拥有的:
class MyClass {
public:
int var;
float* ptr;
double array[3];
MyStruct data;
unique_ptr<MyStruct> smart_ptr;
MyClass() = default;
~MyClass() = default;
}
Is setting the constructor to default
the equivalent of doing: 将构造函数设置为
default
相当于:
MyClass() : var{}, ptr{}, array{}, data{}, smart_ptr{} {}
... or do I need to init each variable? ...或者我需要初始化每个变量吗? (I've tried both in Visual Studio and I get zeros either way, but I'm not sure if that's luck or not.)
(我已经在Visual Studio中尝试了两种方式,无论哪种方式都得到零,但我不确定这是不是运气。)
I'm instancing the class without brackets: MyClass obj;
我正在实现没有括号的类:
MyClass obj;
Is setting the constructor to default the equivalent of doing:
将构造函数设置为默认值相当于:
MyClass() : var{}, ptr{}, array{}, data{}, smart_ptr{} {}
No. It is not. 不它不是。
The line 这条线
MyClass() = default;
is more akin to but not exactly equivalent to: 更接近但不完全等同于:
MyClass() {}
In either case, using 在任何一种情况下,使用
MyClass obj;
results in a default-initialized object whose members are default initialized. 导致默认初始化对象的成员默认初始化。
However, the difference between them when using 但是,使用时它们之间的区别
MyClass obj{};
is that obj
will be zero-initialized with the defaulted default constructor while it will be still default initialized with the user provided default constructor. 是
obj
将使用默认的默认构造函数进行零初始化,而它仍将使用用户提供的默认构造函数进行默认初始化。
To make all of your variables zero-initialized on construction, even if the creator did not request it, one way is: 要使所有变量在构造时零初始化,即使创建者没有请求它,一种方法是:
struct MyClassMembers
{
int var;
float* ptr;
double array[3];
MyStruct data;
unique_ptr<MyStruct> smart_ptr;
};
struct MyClass : MyClassMembers
{
MyClass(): MyClassMembers{} {}
};
Then MyClass m;
然后是
MyClass m;
will use MyClassMembers{}
to initialize the members. 将使用
MyClassMembers{}
初始化成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.