问题
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. 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:
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.)
I'm instancing the class without brackets: MyClass obj;
回答1:
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.
回答2:
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; will use MyClassMembers{} to initialize the members.
来源:https://stackoverflow.com/questions/42048974/does-the-defaulted-default-constructor-initialize-variables-to-zero