Anshuman Anshuman - 1 month ago 6
C++ Question

Converting a automatically allocated std::vector to dynamically allocated std::vector without overhead of copy

Here I have a automatically allocated

std::vector v
. Now Is there a way to construct another dynamically allocated
std::vector
from
v
such that there is no overhead of copy constructor.

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



  1. What happen when destrucotor of
    v
    is called?

  2. Can Someone ellaborate on move constructor of std::vector.

  3. Or I should not worry about this as Compiler will optimise this for me?


AnT AnT
Answer

Since you state that you don't want "overhead of copy constructor", it implies that you no longer need the original vector after creating the "dynamic" one. In that case you can simply do

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

which will use move constructor to construct the new vector. The overhead of moving a vector is almost non-existent.

Again, keep in mind that after doing that your original v is in "moved from" state - in general case it no longer contains the original data. You can reuse v for other purposes. And v is still destructible and its destruction will have no effect on v2.