Reputation: 403
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?
Upvotes: 30
Views: 2057
Reputation: 172964
They have the same effect since C++17. Both construct an object named x
with type std::vector<int>
, which is initialized by the default constructor of std::vector
.
Precisely the 1st one is copy initialization, x
is copy-initialized from a value-initialized temporary. From C++17 this kind of copy elision is guaranteed, as the result x
is initialized by the default constructor of std::vector
directly. Before C++17, copy elision is an optimization:
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:
The 2nd one is default initialization, as a class type x
is initialized by the default constructor of std::vector
.
Note that the behaviors might be different for other types, depending on the type's behavior and x
's storage duration.
Upvotes: 42