Iceman
Iceman

Reputation: 4362

Destructor's functionalities

For a simple class like this:

class X {
public:
//...
private:
int *ptr;
};

X::~X() {
delete ptr;
}

I have written a destructor to free the memory pointed to by ptr. Now, I am wondering, if my destructor stays like this, when is ptr actually destroyed?

Thanks

Upvotes: 0

Views: 96

Answers (4)

HonestHeuristic
HonestHeuristic

Reputation: 336

I think this article might answer most of your questions

"Destructors are implicitly called when an automatic object (a local object that has been declared auto or register, or not declared as static or extern) or temporary object passes out of scope. They are implicitly called at program termination for constructed external and static objects. Destructors are invoked when you use the delete operator for objects created with the new operator."

More specifically:

"The destructors of base classes and members are called in the reverse order of the completion of their constructor:

The destructor for a class object is called before destructors for members and bases are called.

Destructors for nonstatic members are called before destructors for base classes are called.

Destructors for nonvirtual base classes are called before destructors for virtual base classes are called."

Upvotes: 2

thesquaregroot
thesquaregroot

Reputation: 1452

The local version of ptr for a given instance of X will be destroyed when the object goes out of scope. For example:

int main()
{
    X obj;

    for (int i=0; i<10; i++) {
        X tmp;

        // do work with tmp
        ...

        // tmp goes out of scope here
        // the destructor tmp::~X will be called here, immediately after each iteration ends
    }

    // obj goes out of scope here
    // the destructor obj::~X called when the program ends
}

Upvotes: 0

MeNa
MeNa

Reputation: 1487

The destructor will calls in the end of scope where the specific instance are.

Upvotes: 1

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76778

delete invokes the destructor of the object that is being deleted and then frees the memory it occupied.

Upvotes: 1

Related Questions