C ++: delete and Memory leakage
In C ++, you can easily use the new and delete operators to dynamically allocate memory. The default semantics of new is to allocate memory and call constructor, the default semantics of delete is to call the Destructor and release the memory. Note that these two operators are dealing with pointers, and pointer-related operations are a little complicated. Let's look at an example:
Class A {public :~ A () {cout <"destructor of A" <
In this example, B inherits from A, so the pointer of A can point to B. in main (), We dynamically create an object of B, point to it with A pointer from A. When we don't need this object, we should call the destructor of B and release the corresponding memory, so we will delete p directly, what about the output result?
Destructor of;
Only the destructor of A is called, so if we have some memory release operations in the destructor of B, these memory release operations will not be executed, this causes memory leakage. The cause of this problem is that the compiler considers that delete is followed by a static pointer. Therefore, it determines which destructor is called during compilation based on the p type, in this example, p is A pointer of type A, so the destructor of type A is called. To avoid this problem, use the virtual destructor as follows:
# Include
Using namespace std; class A {public: virtual ~ A () {cout <"destructor of A" <
In this example, the destructor of A is modified by virtual, which means that classes derived from A and A both have virtual destructor, and virtual destructor are also virtual functions, therefore, the dynamic binding mechanism of C ++ is used. In this way, when deleting p, the compiler finds that although p is of the type, A has A virtual destructor, therefore, it inserts the code according to the calling mechanism of the virtual function to call the destructor of the object actually pointed to by p during the execution period. Therefore, B's destructor can be found during the execution period, the execution result is as expected: Call the destructor of B first, and then call the destructor of the Base Class.
Destructor of B;
Destructor of;