I have the following code snippet
#include <iostream>
#include <vector>
class Move {
private:
int* data;
public:
void set_data_value(int d) {
*data = d;
}
int get_data_value(){
return *data;
}
Move(int d);
Move(const Move &source);
~Move();
};
Move::Move(int d) {
std::cout << "ctor being called" << std::endl;
data = new int;
*data = d;
}
Move::Move(const Move& source) {
std::cout << "copy ctor being called" << std::endl;
data = new int;
*data = *source.data;
}
Move::~Move() {
std::cout << "deleting Move" << std::endl;
delete data;
}
int main() {
Move x{1};
Move y{x};
std::vector<Move> vec;
vec.push_back(x);
vec.push_back(y);
return 1;
}
Here is the output:
ctor being called
copy ctor being called
copy ctor being called
copy ctor being called
copy ctor being called
deleting Move
deleting Move
deleting Move
deleting Move
deleting Move
My question is: why is the copy constructor being called 4 times when I see only 3 copies? (1 from Move y{x} and two from the two push_back() calls)