Search code examples
c++vectorinitialization-list

C++ Vector Initialization List vs. Assignment


In C++ what is the technical difference between following two ways of initializing a vector?


    vector<int> v_1 {0, 1, 2};

    vector<int> v_2 = {3, 4, 5};

The first one is an initialization list. What is the second one?

I appreciate hints on correct terminology and referring to documentation and different standard versions (C++98 vs. C++11).


Solution

  •     vector<int> v_1 {0, 1, 2};
    

    This is direct-list-initialization, a form of direct-initialization.

    An object v_1 is constructed with the provided values.

        vector<int> v_2 = {3, 4, 5};
    

    This is copy-list-initialization. In this case there is no difference from direct-list-initialization.

    There is still a minor semantic difference, though, as copy-initialization excludes explicit constructors.

    The list-initialization syntax (both version 1 and 2) was introduced in C++11.