"auto x = vector<int>()" 和 "vector<int> x" 有什么区别?

What's the difference between "auto x = vector<int>()" and "vector<int> x"?

有什么区别:

auto x = vector<int>();

vector<int> x;

这两个声明是等价的,还是在 运行 时间复杂度上有一些区别?

它们自 C++17 起具有相同的效果。两者都构造了一个名为 x 且类型为 std::vector<int> 的对象,该对象由 std::vector.

的默认构造函数初始化

恰好第一个是copy initialization, x is copy-initialized from a value-initialized temporary. From C++17 this kind of copy elision是有保证的,因为结果x直接被std::vector的默认构造函数初始化了。在 C++17 之前,复制省略是一种优化:

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:

第二个是default initialization,因为class类型xstd::vector的默认构造函数初始化。

请注意,其他类型的行为可能会有所不同,具体取决于类型的行为和 x 的存储持续时间。