Difference between `vector<int> v;` and `vector<int> v = vector<int>();`

  • A+
Category:Languages

What is the difference between

std::vector<int> v; 

and

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

Intuitively, I would never use the second version but I am not sure there much difference. It feels to me that the second line is simply a default constructor followed by a move assignment operator but I am really not sure.

I am wondering whether the second line is not somehow equivalent to

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

or

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

hence causing the vector itself to be on the heap (dynamically allocated). If it is the case, then the first line would probably be preferred.

How do these lines of code differ?

 


The 1st one is default initialization, the 2nd one is copy initialization; The effect is same here, i.e. initialize the object v via the default constructor of std::vector.

For std::vector<int> v = std::vector<int>();, in concept it will construct a temporary std::vector then use it to move-construct the object v (note there's no assignment here). According to the copy elision (from C++17 it's guaranteed), it'll just call the default constructor to initialize v directly.

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible, as the language rules ensure that no copy/move operation takes place, even conceptually:

  • In the initialization of a variable, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:

    T x = T(T(f())); // only one call to default constructor of T, to initialize x 

BTW: For both cases, no std::vector objects (including potential temporary) will be constructed with dynamic storage duration via new expression.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: