现在的位置: 首页 > 综合 > 正文

设计模式中的单例模式的代码为什么析构函数会多次被调用,而构造函数只调用一次?

2013年05月02日 ⁄ 综合 ⁄ 共 2139字 ⁄ 字号 评论关闭

/********************************************************************
 created: 2006/07/20
 filename:  Singleton.h
 author:  李创
                http://www.cppblog.com/converse/

 purpose: Singleton模式的演示代码
*********************************************************************/

#ifndef SINGLETON_H
#define SINGLETON_H

class Singleton
{
public:
 Singleton();
 ~Singleton();

 // 静态成员函数,提供全局访问的接口
 static Singleton* GetInstancePtr();
 static Singleton  GetInstance();

 void Test();

private:
 // 静态成员变量,提供全局惟一的一个实例
 static Singleton* m_pStatic;
};

#endif

 

/********************************************************************
 created: 2006/07/20
 filename:  Singleton.cpp
 author:  李创
                http://www.cppblog.com/converse/

 purpose: Singleton模式的演示代码
*********************************************************************/

#include "Singleton.h"
#include <iostream>

// 类的静态成员变量要在类体外进行定义
Singleton* Singleton::m_pStatic = NULL;

Singleton::Singleton()
{
     std::cout << "构造函数被调用/n";
}

Singleton::~Singleton()
{
     std::cout << "析构函数被调用/n";
}

Singleton* Singleton::GetInstancePtr()
{
 if (NULL == m_pStatic)
 {
  m_pStatic = new Singleton();
 }

 return m_pStatic;
}

Singleton Singleton::GetInstance()
{
 return *GetInstancePtr();
}

void Singleton::Test()
{
 std::cout << "Test函数被调用!/n";
}

 

/********************************************************************
 created: 2006/07/20
 filename:  Main.cpp
 author:  李创
                http://www.cppblog.com/converse/

 purpose: Singleton模式的测试代码
*********************************************************************/

#include "Singleton.h"
#include <stdlib.h>

 

//析构函数只被调用一次的情形:

int main()
{
 // 不用初始化类对象就可以访问了
 for( int i =0; i < 10; i++)

{

     Singleton::GetInstancePtr()->Test();//程序执行完这一句之后析构函数被调用一次,如果是第一次,构造函数被调用

   //并且构造函数只被调用一次

 

}

 return 0;
}

 

 

程序运行结果:

构造函数被调用
Test函数被调用!
Test函数被调用!
Test函数被调用!
Test函数被调用!
Test函数被调用!
Test函数被调用!
Test函数被调用!
Test函数被调用!
Test函数被调用!
Test函数被调用!

 

析构函数多次被调用的情况:

void Test();

int g_iTest = 0;

int main()
{

 for( int i = 0; i < 5; i++ )//析构函数5次被调用
 {
  Test();
 }

 system("pause");

 return 0;
}

void Test()
{
 g_iTest++;
 printf( "第 %d 次调用成员函数", g_iTest );
 Singleton::GetInstance().Test();
 
 printf( "/n/n" );
}

第 1 次调用成员函数(构造函数被调用)Test!
(析构函数被调用)

第 2 次调用成员函数Test!
(析构函数被调用)

第 3 次调用成员函数Test!
(析构函数被调用)

第 4 次调用成员函数Test!
(析构函数被调用)

第 5 次调用成员函数Test!
(析构函数被调用)

请按任意键继续. . .

抱歉!评论已关闭.