By looking at the example:
#include <iostream>
int wow=0;
class Foo{
int cow = 0;
public:
Foo(){
std::cout << "Foo +\n";
cow = 0;
++wow;
}
Foo(int n){
std::cout << "Foo has " << n << "\n";
cow = n;
++wow;
}
~Foo(){
std::cout << cow << " ~ Foo -\n";
}
void print(){
std::cout << cow << " is the foo#\n";
}
};
int main(){
void * bar = ::operator new(sizeof(Foo));
Foo * a = new(bar) Foo;
*a = Foo(10);
std::cout << wow << std::endl;
a->~Foo();
::operator delete(bar);
return 0;
}
and compiling and running it, the console shows:
Foo+
Foo has 10
10 ~ Foo -
2
10 ~ Foo -
My question is, why is the destructor called upon calling the constructor?
Should the first destructor call be 0 ~ Foo -
? Since that is the first Foo
that is overwritten by Foo(10)
?
In this assignment statement
there is created a temporary object of the type
Foo
that is assigned to the object specified by the expression*a
using the default copy assignment operator (neither copy or move constructor is called here). After the assignment the temporary object is deleted. The undeclared variablecow
(it seems it is a data member of the classFoo
) of the object pointed to by the pointera
now contains the same value10
. And in the end of the program the object pointed to by the pointera
is also deleted.As a result you will get two messages
The first one is generated by the destructor of the temporary object and the second one is generated by the object pointed to by the pointer
a
.