RAII Resource Handling

I have a RAII class:


template<typename T> class RAII { public: explicit RAII( T* p = 0 ): p_(p){} ~RAII() {delete p_;} T& operator*() const { return p_;} T* operator‐>() const{ return p_;} }; 

 { RAII<std::vector<int>> r(new std::vector<int>()); std::cout<<r‐>size()<<std::endl; } // The std::vector<int> is automatically deallocated 

I know when I run out of scope, my destructor will be called. ~RAII() {delete P_};

My question is:

What is my destructor called?

+7
source share
2 answers

When an exception is thrown and control passes from the try block to the handler, C ++ runtime calls destructors for all automatic objects built from the beginning of the try block. This process is called stack expansion. Automatic objects are destroyed in the reverse order of their design. (Automatic objects are local objects that were declared automatically or registered or not declared as static or extern. An automatic object x is deleted whenever the program exits the block in which x is declared.)

If an exception is thrown when constructing an object consisting of subobjects or array elements, destructors are called only for those subobjects or array elements that were successfully created before the exception was thrown. The destructor for the local static object will be called only if the object was successfully constructed.

If during the unwinding of packets the destructor throws an exception and the exception is not processed, the terminate () function is called.

Example: see disassembly below. You will see that the destructor is already pushed onto the stack.

 class Test { public: Test() { std::cout<<"C'tor\n"; } ~Test() { std::cout<<"D'tor\n"; } } int main()//_TCHAR* argv[]) { Test(); } 00DD9C30 55 push ebp 00DD9C31 8B EC mov ebp,esp 00DD9C33 81 EC CC 00 00 00 sub esp,0CCh 00DD9C39 53 push ebx 00DD9C3A 56 push esi 00DD9C3B 57 push edi 00DD9C3C 8D BD 34 FF FF FF lea edi,[ebp-0CCh] 00DD9C42 B9 33 00 00 00 mov ecx,33h 00DD9C47 B8 CC CC CC CC mov eax,0CCCCCCCCh 00DD9C4C F3 AB rep stos dword ptr es:[edi] 23: 24: Test(); 00DD9C4E 8D 8D 3B FF FF FF lea ecx,[ebp-0C5h] 00DD9C54 E8 67 7C FF FF call Test::Test (0DD18C0h) 00DD9C59 8D 8D 3B FF FF FF lea ecx,[ebp-0C5h] 00DD9C5F E8 03 76 FF FF call Test::~Test (0DD1267h) 25: } 
+6
source

The compiler automatically generates code to call local variable destructors. *


* Technically, they are known as "objects with automatic storage time." It should be clear why!
+4
source

All Articles