zhangzhimin zhangzhimin - 7 months ago 52
C++ Question

The initializer list in c++

See the following codes:

std::vector<int> v1{1, 2, 3};
std::vector<int> v2 = {1, 2, 3};

My questions are:

  1. Is there any difference between the two? I know the first one must be list initialization, but how about the second?

  2. Because there is a assign sign for the second, it makes me think that the compiler will use the
    to create a temporary
    first, then it use copy constructor to copy the temp
    . Is this the fact?


The two (direct-list-initialization vs copy-list-initialization) are exactly the same in this case. No temporary std::vector is constructed and there's no std::vector::operator= called. The equals sign is part of the initialization syntax.

There would be a difference if std::vector's constructor overload no. 7 was marked explicit, in which case any copy-initialization fails, but that would be a flaw in the design of the standard library.