首页 > 解决方案 > `向量之间的区别v;`和`向量v = 向量();`

问题描述

和有什么区别

std::vector<int> v;

std::vector<int> v = std::vector<int>();

直觉上,我永远不会使用第二个版本,但我不确定是否有任何区别。在我看来,第二行只是一个默认构造函数,它构建了一个临时对象,然后由移动赋值运算符移动。

我想知道第二行是否不等于

std::vector<int> v = *(new std::vector<int>()); 

因此导致向量本身在堆上(动态分配)。如果是这种情况,那么在大多数情况下,第一行可能是首选。

这些代码行有何不同?

标签: c++constructorinitialization

解决方案


从 C++17 开始,没有任何区别。

There's one niche use case where the std::vector = std::vector initialization syntax is quite useful (albeit not for default construction): when one wants to supply a "count, value" initializer for std::vector<int> member of a class directly in the class's definition:

struct S {
  std::vector<int> v; // Want to supply `(5, 42)` initializer here. How?
};

In-class initializers support only = or {} syntax, meaning that we cannot just say

struct S {
  std::vector<int> v(5, 42); // Error
};

If we use

struct S {
  std::vector<int> v{ 5, 42 }; // or = { 5, 42 }
};

the compiler will interpret it as a list of values instead of "count, value" pair, which is not what we want.

So, one proper way to do it is

struct S {
  std::vector<int> v = std::vector(5, 42);
};

推荐阅读