apchar
apchar

Reputation: 59

why is a destructor IMPLICITLY called twice on same object?

Consider the following snippet of c++ and the output below it.

#include <iostream>
using namespace std;

class One {
public:
    One(int num);
    One();
    ~One();
private:
    int number;
};

One::One(int num) {
    number = num;
    cout << "One constructor number = " << number << endl;
}

One::One() {
    number = 0;
    cout << "default One constructor\n";
}

One::~One() {
    cout << "One destructor. number = " << number << endl;
    number = 0;
}

int main() {
    One uno;
    uno = One(2);
    return 0;
}

default One constructor

One constructor number = 2

One destructor. number = 2

One destructor. number = 2

Notice the replication of the last line. I understand (& hate) why the default constructor is called by the first line in main, but the destructor for that instance is never called. Instead the destructor for the second instance is implicitly called twice. Why? And how is the variable 'number' able to persist at number=2 ? The destructor set it to 0. It's like the garbage collector is trying to delete the instance created by the default constructor but hitting an old copy of the 2nd. This is a trivial example but it's a real problem when it comes time to delete pointers.

Upvotes: 1

Views: 1310

Answers (1)

nneonneo
nneonneo

Reputation: 179432

One uno;   // Create a default One instance - default constructor called.
uno = One(2); // Create a temporary One instance - number constructor called and prints 2.
              // Assign temporary to uno - uno now has the number 2.
              // Destroy temporary One instance - destructor called and prints 2.
return 0;
// uno destroyed. It has the number 2, so this also prints 2.

Or, in terms of the output you saw:

default One constructor // from uno construction
One constructor number = 2 // from temporary One(2) construction
One destructor. number = 2 // from temporary One(2) destruction
One destructor. number = 2 // from uno destruction (since number has changed)

Upvotes: 7

Related Questions