3.1.3.内存泄漏检测
通过vld进行检测内存泄漏,当未添加CGarbo类,内存泄漏一个字节,即该空单例类实例所占的1个字节,如下。添加CGarbo类及静态成员变量后,内存无泄漏。
[html] view plaincopy
Visual Leak Detector Version 2.3 installed.
WARNING: Visual Leak Detector detected memory leaks!
---------- Block 1 at 0x003AC038: 1 bytes ----------
Call Stack:
d:\microsoft visual studio 9.0\projects\testcpp\testsingleton\singleton1.h (11): TestSingleton.exe!CSingleton1::getInstance + 0x7 bytes
d:\microsoft visual studio 9.0\projects\testcpp\testsingleton\testsingleton.cpp (12): TestSingleton.exe!wmain
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (583): TestSingleton.exe!__tmainCRTStartup + 0x19 bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (403): TestSingleton.exe!wmainCRTStartup
0x7C81776F (File and line number not available): kernel32.dll!RegisterWaitForInputIdle + 0x49 bytes
Data:
CD
3.2.静态局部变量实现
3.2.1.特点
A.无需考虑内存释放问题。
B.禁用类拷贝和类赋值。
3.2.2.示例
[cpp]
//Singleton2.h
#pragma once
class CSingleton2
{
public:
static CSingleton2& getInstance()
{
static CSingleton2 instance;
return instance;
}
private:
CSingleton2();
CSingleton2(const CSingleton2 &);
CSingleton2 & operator = (const CSingleton2 &);
};
3.2.3.无内存泄漏相关问题