В C ++ 11 и более поздних версиях это похоже на различия между инициализацией default и value в зависимости от того, как я определяю свой класс, результат инициализации может отличаться.Например, посмотрите на классы ниже или 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
, не инициализируются в предоставляемом пользователем конструкторе по умолчанию.Если это так, то мне следует либо предоставить инициализаторы элементов по умолчанию для всех элементов, либо определить конструктор по умолчанию, который инициализирует все элементы.Есть ли разница между значением по умолчанию конструктора по умолчанию и использованием инициализаторов элементов по умолчанию для всех элементов по сравнению с определением конструктора по умолчанию, который инициализирует все элементы в списке инициализаторов элементов?