在C ++ 11及更高版本中,由于默认和值初始化之间的差异(取决于我如何定义类),似乎初始化的结果可能会有所不同。例如,查看下面的类或http://coliru.stacked-crooked.com/a/b45acc5acf847e73:
#include <iostream>
#include <string>
#include <vector>
class ClassWithDefaultedConstructor {
public:
ClassWithDefaultedConstructor() = default;
int GetInt() const { return member_int_; }
bool GetBool() const { return member_bool_; }
std::string GetString() const { return member_string_; }
private:
int member_int_;
bool member_bool_;
std::string member_string_;
int member_int_array_[5];
};
class ClassWithUserProvidedDefaultConstructor {
public:
ClassWithUserProvidedDefaultConstructor() : member_int_() {}
int GetInt() const { return member_int_; }
bool GetBool() const { return member_bool_; }
std::string GetString() const { return member_string_; }
private:
int member_int_;
bool member_bool_;
std::string member_string_;
int member_int_array_[5];
};
class ClassWithDefaultedConstructorAndDefaultMemberInitializers {
public:
ClassWithDefaultedConstructorAndDefaultMemberInitializers() = default;
int GetInt() const { return member_int_; }
bool GetBool() const { return member_bool_; }
std::string GetString() const { return member_string_; }
private:
int member_int_{};
bool member_bool_{};
std::string member_string_;
int member_int_array_[5]{};
};
int main()
{
std::cout << "Hello World!" << std::endl;
// Default initialization: int and bool members will have indeterminate values
ClassWithDefaultedConstructor default_init1;
// Value initialization: int and bool members will be zero-initialized
ClassWithDefaultedConstructor value_init1{};
// Default initialization: member_int_ is value initialized to 0 in constructor
// member initiazer list but member_bool_ and member_int_array_ have indeterminate values
ClassWithUserProvidedDefaultConstructor default_init2;
// Value initialization: member_bool_ and member_int_array_ are default initialized
// and have indeterminate values
ClassWithUserProvidedDefaultConstructor value_init2{};
// Default initialization: int and bool members are value initialized to 0 because
// of the default member initializers value initializing them
ClassWithDefaultedConstructorAndDefaultMemberInitializers default_init3;
// Value initialization: same as if no default member initializers were used
ClassWithDefaultedConstructorAndDefaultMemberInitializers value_init3{};
}
因此,根据类的客户端选择声明对象(带有或不带有初始化程序)的方式,对象的起始状态将有所不同。这是真的?我在开源项目中遇到了很多代码,这些代码中标准库中类类型的成员(例如std::string
未在用户提供的默认构造函数中初始化)。如果是这样,我似乎应该为所有成员提供默认的成员初始化程序,或者定义一个初始化所有成员的默认构造函数。缺省默认构造函数和对所有成员使用缺省成员初始化器与定义初始化成员初始化器列表中的所有成员的缺省构造器之间有什么区别吗?
= default
导致您的成员的默认初始化。
对于内置类型,没有什么。
对于类类型,这是默认的构造函数。
如果您需要初始化某件事,请将其初始化。如果您不这样做,请不要。如果它是类类型的成员(例如std::string
)并且默认构造已足够,则您无需执行任何操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句