c++11vectorinitialization

Default constructor, which one is more correct / idiomatic?


Is there any difference between:

class A {
    std::vector<int> vec {1, 2, 3};
public:
    // more stuff...    
};

A a; // implicit default constructor

class B {
    std::vector<int> vec;
public:
    B() : vec {1, 2, 3} {}
    // more stuff...
}

B b; // default constructor

Which one is faster / more idiomatic / correct in C++14?

In my class I have 3 members: a static const initialized inside the class, a Boolean initialized to true and a non initialized std::vector.

My two constructors initialize the std::vector and, when necessary I change the Boolean to false. I want the default constructor to initialize the std::vector with 0? Which options from above is more correct?

If I initialized the std::vector member, what would happen If I did this? PS: My class is not a POD.

class B {
    std::vector<int> vec {1, 2, 3}; // already initialized vector
public:
    B(std::vector<int> const & data)
        : vec {data} // would it still be initialization or copy-assignment?
    {}
}

B b; //default constructor

Solution

  • There's no practical difference between your first two examples. In-class initializers are useful when you want to use the same initializer in multiple constructors; constructor initializer lists are mandatory when you want to use different inititalizers in different constructors.

    When you have both an in-class initializer and a constructor member initializer, the in-class initializer is ignored for that constructor. There's still just one initialization and no assignment.