C++ destructor called after calling constructor

203 views Asked by At

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)?

1

There are 1 answers

6
Vlad from Moscow On BEST ANSWER

In this assignment statement

 *a = Foo(10);

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 variable cow (it seems it is a data member of the class Foo) of the object pointed to by the pointer a now contains the same value 10. And in the end of the program the object pointed to by the pointer a is also deleted.

As a result you will get two messages

10 ~ Foo -
10 ~ Foo -

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.