Forms of list initialization

只愿长相守 提交于 2020-02-04 03:22:22

问题


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?


回答1:


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.




回答2:


They're both list initialization (since C++11). The first one is direct-list-initialization, and the second one is copy-list-initialization.

  1. Is there any difference between the two?

For direct-list-initialization both explicit and non-explicit constructors will be considered, while copy-list-initialization only non-explicit constructors might be called. For this case (i.e. std::vector) the actual result is same.

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

No. Even for the copy-list-initialization, the object will be constructed by the appropriate constructor directly. For this case, a temporary std::initializer_list<int> will be created and then std::vector::vector(std::initializer_list<T>, const Allocator& = Allocator()) will be called to construct v2.



来源:https://stackoverflow.com/questions/38582981/forms-of-list-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!