Anshuman Anshuman - 6 months ago 27
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
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
    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?


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.