FAQ 20.05 What happens when a destructor is executed?

The destructor automatically calls the destructors for all member objects and all immediate nonvirtual base classes. First, the destructor's body ({...}) is executed, then the destructors for member objects are called in the reverse order that the member objects appear in the class body, then the destructors for immediate base classes are called (in the reverse order they appear in the class declaration). Virtual base classes are special their destructors are called at the end of the most derived class's destructor (only).

For example, suppose lock(int) and unlock(int) provide the primitives to manage mutual exclusion. The C++ interface to these primitives would be a Lock class, whose constructor calls lock(int) and whose destructor calls unlock(int).

 #include <iostream> using namespace std; void lock(int i) throw() {   cout << "pretend we acquire lock #" << i << '\n';   //In reality, this would manipulate semaphore #i   // (or use some other mutual exclusion primitive) } void unlock(int i) throw() {   cout << "pretend we release lock #" << i << '\n';   //In reality, this would manipulate semaphore #i   // (or use some other mutual exclusion primitive) } class Lock { public:   Lock(int lockNum) throw();  ~Lock()            throw(); protected:   int lockNum_; private:   // These are never defined (copying a Lock is senseless)   Lock(const Lock&);   Lock& operator= (const Lock&); }; inline Lock::Lock(int lockNum) throw() : lockNum_(lockNum) { lock(lockNum_); } inline Lock::~Lock() throw() { unlock(lockNum_); } void multiThreadedFunction() throw() {   cout << "no mutual exclusion here\n";   {     Lock lock(42);   //Pretend this is Critical section (42)     cout << "lock provides mutual exclusion here\n";   }   cout << "no mutual exclusion here\n"; } 

A whimsical developer might rename class Lock to class Critical, so that if the user code declared an object named section, Lock lock(42) would then become Critical section(42). But regardless of the names of the class and its object, the important point is that there is no need to explicitly unlock the semaphore. This eliminates a potential (and dangerous!) source of errors.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net