I am practising to execute move constructor every time by passing R-Value. But Sometimes the Deep copy constructor is getting called it is not supped to.
I am inserting an R-value object inside a vector. What is the logical flaw in this code?
I have tried debugging, I don't understand as to why deep copy constructor is called after the object was moved?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class example{
private:
int *pointer;
public:
//constructor
example(int d){
pointer = new int;
*pointer = d;
cout<<"Constructor Called"<<endl;
}
// deep copy
example(const example &source){
pointer = new int;
*pointer= *source.pointer;
cout<<"deep copy made"<<endl;
}
// Move Constructor
example(example &&source):pointer{source.pointer}{
source.pointer = nullptr;
cout << "object moved"<<endl;
}
~example() {
delete pointer;
cout << "Destroyed"<<endl;
}
};
int main()
{
vector <example> vec;
vec.push_back(example{300});
vec.push_back(example{300});
vec.push_back(example{300});
vec.push_back(example{300});
return 0;
}
If the code was right it will always use MOVE constructor, and it will avoid deep copy