Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forms of list initialization

See the following code:

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

My questions are:

  1. Is there a 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 std::initializer_list to create a temporary vector first, then it use copy constructor to copy the temp vector to v2. Is this the fact?

like image 408
zhangzhimin Avatar asked May 18 '26 03:05

zhangzhimin


1 Answers

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.

like image 196
LogicStuff Avatar answered May 20 '26 18:05

LogicStuff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!