I have a ArrayWrapper class which implements both move and copy constructor.
I have 2 Questions.
You can see that in my code, the copy constructor
ArrayWrapper (ArrayWrapper& other)
is exactly same as move constructorArrayWrapper (ArrayWrapper&& other)
!? Both works just the same and has the same elapsed time. (I commented out the original copy constructor) How can the copy and move constructor use the same code and still work?The code actually isn't hitting the move constructor (I suspect this is why my first question works), I put a comment in both functions, and the output does not show that the move constructor is being called, even though I am passing an rvalue reference
ArrayWrapper d3(ArrayWrapper(10000000));
. What am I doing wrong?#include <bits/stdc++.h> #include <chrono> using namespace std; using namespace std::chrono; class ArrayWrapper { public: ArrayWrapper () : _p_vals( new int[ 64 ] ) , _size( 64 ) { cout<<"?"<<endl; } ArrayWrapper (int n) : _p_vals( new int[ n ] ) , _size( n ) { } ArrayWrapper (ArrayWrapper&& other) : _p_vals( other._p_vals ) , _size( other._size ) { cout<<"Move"<<endl; other._p_vals = NULL; other._size = 0; } ArrayWrapper (ArrayWrapper& other) : _p_vals( other._p_vals ) , _size( other._size ) { cout<<"Copy constructor"<<endl; other._p_vals = NULL; other._size = 0; } /* // copy constructor ArrayWrapper (const ArrayWrapper& other) : _p_vals( new int[ other._size ] ) , _size( other._size ) { for ( int i = 0; i < _size; ++i ) { _p_vals[ i ] = other._p_vals[ i ]; } } */ void generate(){ for(int i=0; i<_size; i++){ _p_vals[i] = i; } } ~ArrayWrapper () { delete [] _p_vals; } void print(){ for(int i=0; i<_size;i++){ cout<<_p_vals[i]<<" "; } cout<<endl; } private: int *_p_vals; int _size; }; int main(){ auto start = high_resolution_clock::now(); ArrayWrapper d(10000000); ArrayWrapper d2(d); //deep copy auto stop= high_resolution_clock::now(); auto duration = duration_cast<microseconds>(stop - start); cout << duration.count() << endl; auto start2 = high_resolution_clock::now(); ArrayWrapper d3(ArrayWrapper(10000000)); //shallow copy auto stop2 = high_resolution_clock::now(); auto duration2 = duration_cast<microseconds>(stop2 - start2); cout << duration2.count() << endl; }