c++ - `向量之间的区别v;`和`向量v = 向量();`
问题描述
和有什么区别
std::vector<int> v;
和
std::vector<int> v = std::vector<int>();
直觉上,我永远不会使用第二个版本,但我不确定是否有任何区别。在我看来,第二行只是一个默认构造函数,它构建了一个临时对象,然后由移动赋值运算符移动。
我想知道第二行是否不等于
std::vector<int> v = *(new std::vector<int>());
因此导致向量本身在堆上(动态分配)。如果是这种情况,那么在大多数情况下,第一行可能是首选。
这些代码行有何不同?
解决方案
从 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);
};
推荐阅读
- wpf - 如何在 WPF 应用程序中以编程方式插入文本时调整文本框的大小?
- php - PHP在循环内继续循环
- clojure - Onyx 中的水印触发器不会触发
- swift - 模拟器 ipad air 2 中的快速标签栏项目间距不正确
- javascript - 是否可以在 Dynamics CRM 中显示 Web 资源的导航栏?
- ms-access - MSAccess VBA 将单个附件保存到文件夹
- bash - 脚本停止,尽管“set -e”是在读取后设置的
- ios - 确定 urlsession.shared 和 Json 解析何时完成
- c# - 如何正确返回对象属性的子集
- r - 使用 R 解析 YAML 前端