Apr 26, 2021 at 1:51pm UTC
By looking at the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#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)?
Last edited on Apr 26, 2021 at 2:34pm UTC
Apr 26, 2021 at 2:02pm UTC
*a = Foo(10);
This creates a temporary, unnamed Foo object and then assigns it to *a using a compiler-generated assignment operator overload, which would look something like:
1 2 3 4 5 6
Foo& operator =(const Foo& foo)
{
cow = foo.cow;
return *this ;
}
The temporary object is then destroyed.
Last edited on Apr 26, 2021 at 2:06pm UTC
Apr 26, 2021 at 2:37pm UTC
Can you give me another example of it please?
Apr 26, 2021 at 2:41pm UTC
An example of what? What is the thing that you don't understand?
Apr 26, 2021 at 2:47pm UTC
@MikeyBoy I still dont get as why a temporary constructor will be destroyed with a message of 10 ~ Foo -? A temporary constructor Foo has a member cow with a value of 0 right?
Apr 26, 2021 at 2:48pm UTC
Please can you give me something like an indepth explanation or step by step on what is going on behind the scence of the line
*a = Foo(10);
Apr 26, 2021 at 3:16pm UTC
Okay I already get it. Thanks for your help.