[英]What's the difference between “auto x = vector<int>()” and “vector<int> x”?
What is the difference between: 有什么区别:
auto x = vector<int>();
and 和
vector<int> x;
Are both of these declarations equivalent, or is there some difference with the run-time complexity? 这两个声明都是等效的,还是与运行时复杂性有一些区别?
They have the same effect since C++17. 它们与C ++ 17相同,效果相同。 Both construct an object named
x
with type std::vector<int>
, which is initialized by the default constructor of std::vector
. 两者都构造一个名为
x
的对象,其类型为std::vector<int>
,它由std::vector
的默认构造函数初始化。
Precisely the 1st one is copy initialization , x
is copy-initialized from a value-initialized temporary. 准确地说,第一个是复制初始化 ,
x
是从值初始化的临时复制初始化的 。 From C++17 this kind of copy elision is guaranteed, as the result x
is initialized by the default constructor of std::vector
directly. 从C ++ 17可以保证这种复制省略 ,因为结果
x
直接由std::vector
的默认构造函数初始化。 Before C++17, copy elision is an optimization: 在C ++ 17之前,copy elision是一个优化:
even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:
即使它发生并且没有调用复制/移动(因为C ++ 11)构造函数,它仍然必须存在并且可访问(好像根本没有发生优化),否则程序是不正确的:
The 2nd one is default initialization , as a class type x
is initialized by the default constructor of std::vector
. 第二个是默认初始化 ,因为类型
x
由std::vector
的默认构造函数初始化。
Note that the behaviors might be different for other types, depending on the type's behavior and x
's storage duration. 请注意,其他类型的行为可能不同,具体取决于类型的行为和
x
的存储持续时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.