struct X
{
// default c
X()
{
i++;
j = i;
std::cout<<"X() "<<j<<std::endl;
}
// copy constructor
X(const X&) { std::cout<<"X(const X&)"<<std::endl; }
// copy assignment operator
X& operator=(const X&)
{
std::cout<<"operator= "<<j<<std::endl;
}
// destructor
~X() { std::cout<<"~X() "<<j<<std::endl; } // destructor
static int i;
int j;
};
int X::i = 0;
X fa()
{
return X();
}
X& fb(X& x)
{
return x;
}
int main()
{
X x1;
X* x2 = new X;
std::cout << "\n----- X x3 = fa();\n";
X x3 = fa(); // Q1
std::cout << "\n----- X x4 = fb(x1);\n";
X x4 = fb(x1); // Q2
std::vector<X> vx;
vx.psh_back(x1);
std::cout << "\n----- vx.push_back(*x2);\n";
vx.push_back(*x2); // Q3
return 0;
}
Running this program produces the following output,
X() 1
----- X x3 = fa();
X() 2
----- X x4 = fb(x1);
X(const X&)
X() 3
X(const X&)
----- vx.push_back(*x2);
X(const X&)
X(const X&)
~X() 0
~X() 0
~X() 0
~X() 0
~X() 2
~X() 1
Its not clear to me what is happening in Q1, Q2, Q3.
In Q1, why is the copy constructor skipped, and why is the destructor not called when the function goes out of scope?
In Q2, why is the final call to the copy constructor and not the assignment operator?
In Q3, why is the copy constructor called twice before the destructor? As the push_back causes the existing element to be copied into the next to last address shouldn't the order be copy constructor, destructor, copy constructor?