// Method One
class ClassName
{
public:
ClassName() : m_vecInts() {}
private:
std::vector<int> m_vecInts;
};
// Method Two
class ClassName
{
public:
ClassName() {} // do nothing
private:
std::vector<int> m_vecInts;
};
What is the correct way to initialize the std::vector
data member of the class?
Do we have to initialize it at all?
See http://en.cppreference.com/w/cpp/language/default_initialization
Default initialization is performed in three situations:
- when a variable with automatic storage duration is declared with no initializer
- when an object with dynamic storage duration is created by a new-expression without an initializer
- when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.
The effects of default initialization are:
- If T is a class type, the default constructor is called to provide the initial value for the new object.
- If T is an array type, every element of the array is default-initialized.
- Otherwise, nothing is done.
Since std::vector
is a class type its default constructor is called. So the manual initialization isn't needed.