About the release of C + + global variables, has been relatively vague, today did a test:
The Memory leak Detection tool used is: Visual Leak Detector can be downloaded directly to the official website
First, on the global variable pointer type, the program at the exit, the dynamically created object also exists in memory, resulting in memory leaks;
1#include <stdlib.h>2 3#include"vld.h" //Memory Leak Detection Tool4 #pragmaComment (lib, "Vld.lib")5 6 using namespacestd;7 8 intnum =Ten;9 int* pages =New int(Ten);Ten Const intindex =Ten; One Static int* Pcount =New int( the); A Static intAge = -; - - intMain () the { - Deletepages;//for global pointer types, there is a memory leak if the release is not displayed -Pages =NULL; - + DeletePcount; -Pcount =NULL; + A intb = A; at return 0; -}
Second, the members assigned through new within the function need to consider whether the object needs to be disposed, and whether or not to define pointers is not related;
1#include <stdio.h>2#include <iostream>3 4#include"vld.h" //Memory Leak Detection Tool5 #pragmaComment (lib, "Vld.lib")6 7 using namespacestd;8 9 classWidgetsTen { One Public: A widgets () - : M_pnyear (NULL) - { the } - -~widgets () - { + if(m_pnyear) - { +Std::cout <<"destructor Widget"<<Endl; A Deletem_pnyear; atM_pnyear =NULL; - } - } - - voidSetyear (int*pyear) - { inM_pnyear =pyear; - } to + Private: - int*m_pnyear; the }; * $ intMain ()Panax Notoginseng { - //Pi1 is generated from new, and if not removed later, memory leaks the int* Pi1 =New int( -); + Deletepi1; API1 =NULL; the + //At this point the object is built on the stack, so the Wiget destructor is automatically called when the function exits - //Thus the PI2 is managed by the Widget object and does not need to be shown here again, $ widget widgets; $ int* Pi2 =New int( +);//But after the destruction, it becomes a wild pointer . - widget. Setyear (PI2); - the //This type of occurrence, similar to the pi1 defined above, must show the delete -widget* Pwid =Newwidgets ();Wuyi DeletePwid; thePwid =NULL; - Wu intb = A; - return 0; About}View Code
C + + Memory leak summary