Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you guarantee destructor order when objects are declared on a stack?

Tags:

I have code that controls a mutex lock/unlock based on scope:

void PerformLogin() {     ScopeLock < Lock > LoginLock( &m_LoginLock );      doLoginCommand();      ScopeLock < SharedMemoryBase > MemoryLock( &m_SharedMemory );      doStoreLogin();      ... } 

Can I guarantee that MemoryLock will be destructed before LoginLock?

like image 696
Alan Avatar asked Aug 07 '09 16:08

Alan


People also ask

What is the order of execution of destructor in following statement?

The body of an object's destructor is executed, followed by the destructors of the object's data members (in reverse order of their appearance in the class definition), followed by the destructors of the object's base classes (in reverse order of their appearance in the class definition).

Why destructors are called in reverse order?

Objects are always destroyed in reverse order of their creation. The reason for reverse order is, an object created later may use the previously created object.

Does destructor get called automatically?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ).

Does destructor destroy the object?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.


1 Answers

Yes, it is. In any particular scope local objects are destroyed in the reverse order that they were constructed.

like image 57
CB Bailey Avatar answered Sep 28 '22 09:09

CB Bailey