http://blog.csdn.net/infoworld/article/details/45560219
Scene:
1. C + + classes have constructors and destructors that are used to release resources when class objects are deleted (or when local variables are automatically destroyed).
2. C + + Class object Pointers in many cases need to be assigned to void* universal pointers to achieve the purpose of transmitting objects, but often this void* pointer is the source of memory leaks or program errors,
This is why C + + has a generic purpose, and it is also designed to eliminate this object uncertainty at compile time, avoiding delete or use errors.
3. When you delete void* type, be careful to convert to class type only delete, such as delete (A *) Data_;
OK, look at the code, what's wrong with the following code?
[CPP]View Plaincopy
- Test_class.cpp: Defines the entry point of the console application.
- //
- #include "stdafx.h"
- #include <iostream>
- Class A
- {
- Public
- A ()
- {
- i = new int;
- }
- ~a ()
- {
- Delete I;
- }
- int* i;
- };
- Class B
- {
- Public
- B (void* data)
- {
- Data_ = data;
- }
- ~b ()
- {
- Delete Data_;
- }
- void* Data_;
- };
- Template <class t>
- Class C
- {
- Public
- C (t* data)
- {
- Data_ = data;
- }
- ~c ()
- {
- Delete Data_;
- }
- t* Data_;
- };
- void Wrong ()
- {
- A *a = new A ();
- b b (a); when the function returns, A's destructor does not call
- }
- void Right ()
- {
- A *a = new A ();
- C<a> c (A); when the function returns, A's destructor is called
- }
- int _tmain (int argc, _tchar* argv[])
- {
- Wrong ();
- Right ();
- return 0;
- }
Analytical:
B in the destructor Deleta Data_, looking at the disassembly code, and did not call the destructor.
[Plain]View Plaincopy
- 011d1643 mov Eax,dword ptr [this]
- 011d1646 mov ecx,dword ptr [eax]
- 011d1648 mov dword ptr [EBP-0D4H],ECX
- 011D164E mov edx,dword ptr [ebp-0d4h]
- 011d1654 push edx
- 011d1655 call operator Delete (11d1096h)
C in the destructor Deleta Data_, look at the disassembly code, there are call destructors.
[Plain]View Plaincopy
- 011d1883 mov Eax,dword ptr [this]
- 011d1886 mov ecx,dword ptr [eax]
- 011d1888 mov dword ptr [EBP-0D4H],ECX
- 011d188e mov edx,dword ptr [ebp-0d4h]
- 011d1894 mov dword ptr [Ebp-0e0h],edx
- 011D189A cmp DWORD ptr [ebp-0e0h],0
- 011d18a1 JE c<a>::~c<a>+58h (11d18b8h)
- 011D18A3 Push 1
- 011D18A5 mov ecx,dword ptr [ebp-0e0h]
- 011d18ab call A:: ' scalar deleting destructor ' (11D102DH)
- 011D18B0 mov dword ptr [Ebp-0e8h],eax
- 011d18b6 jmp c<a>::~c<a>+62h (11D18C2H)
Considerations for delete class object pointers]