列表初始化的形式

列表初始化的形式

本文介绍了列表初始化的形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见以下代码:

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

我的问题是:

  1. 两者之间有区别吗?我知道第一个必须是列表初始化,但是第二个应该如何?

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

因为第二个有一个赋号,所以我认为编译器将首先使用std::initializer_list创建一个临时vector,然后使用复制构造函数复制临时vectorv2.这是事实吗?

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?

推荐答案

两者( direct-list-initialization copy-list-initialization )在这种情况下是完全相同的.没有构造临时std::vector,也没有调用std::vector::operator=.等号是初始化语法的一部分.

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.

如果 std::vector的构造函数重载号为no,则会有所不同. 7 被标记为explicit,在这种情况下,任何复制初始化都会失败,但这将是标准库设计的一个缺陷.

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.

这篇关于列表初始化的形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 10:28