I've been testing some C++11 features from some some. I came across r-value references and move constructors.
I implemented my first move constructor, here it is:
#include <iostream>
#include <vector>
using namespace std;
class TestClass{
public:
TestClass(int s):
size(s), arr(new int[s]){
}
~TestClass(){
if (arr)
delete arr;
}
// copy constructor
TestClass(const TestClass& other):
size(other.size), arr(new int[other.size]){
std::copy(other.arr, other.arr + other.size, arr);
}
// move constructor
TestClass(TestClass&& other){
arr=other.arr;
size=other.size;
other.arr=nullptr;
other.size=0;
}
private:
int size;
int * arr;
};
int main(){
vector<TestClass> vec;
clock_t start=clock();
for(int i=0;i<500000;i++){
vec.push_back(TestClass(1000));
}
clock_t stop=clock();
cout<<stop-start<<endl;
return 0;
}
The code works fine. Anyway putting a std::cout inside the copy constructor i noticed that it gets called! And a lot of times.. (move constructor 500000 times, copy constructor 524287 times).
What surprised me more is that if i comment out the copy constructor from the code, the whole program gets a lot faster, and this time the move constructor is called 1024287 times.
Any clue?
delete[]
, and you don't need theif (arr) ...
in the destructor. So the destructor should be simply~TestClass(){ delete[] arr; }
. – Alidelete[]
without the if: (1) if thenew
throws in the initialization, the destructor won't be called (2) otherwise you either point to a valid address (3) or have anullptr
and it is always safe to delete anullptr
(guaranteed by the standard). – Ali