0909LQ 2015-07-21 14:52 采纳率: 100%
浏览 2746
已采纳

多线程下Singleton模式

 //singleton.h

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#include "synobj.h"

template<typename T> 
class Singleton
{
public:
    static T* Instance();

protected:

private:
    Singleton();
    ~Singleton();
    Singleton(Singleton& );
    Singleton& operator = (Singleton& );
    static void Destory();

private:
    static T*  _instance;
    static Mutex _mutex;
};
 //singleton.cpp

//volatile的作用是: 作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值.

#include "stdafx.h"
#include "singleton.h"
#include <iostream>
#include <stdlib.h>

using namespace std;

template<typename T> T*  Singleton<T>::_instance = NULL;
template<typename T> Mutex Singleton<T>::_mutex;

template<typename T>
Singleton<T>::Singleton()
{

}

template<typename T> 
Singleton<T>::~Singleton()
{

}

template<typename T> 
T* Singleton<T>::Instance()
{
    if(_instance == NULL )
    {
        Lock lock(_mutex);
        if(_instance == NULL)
        {
            T* temp = new T;
            _instance = temp;
            //_instance = new T();
            atexit(Destory);
        }
    }
    return _instance;
}

template<typename T>
void Singleton<T>::Destory()
{
    if(NULL != _instance)
    {
        delete _instance;
        _instance = NULL;
    }
}
 // Singleton20.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "singleton.h"
#include "synobj.h"
#include <stdio.h>
#include <iostream>

using namespace std;

class A:public Singleton<A>
{
public:
    void DoSomething()
    {
        cout<<"hello DoSomething"<<endl;
    }

};


int _tmain(int argc, _TCHAR* argv[])
{
    A* a = A::Instance();
    a->DoSomething();

    getchar();
    return 0;
}

图片说明
我的代码大致是这样的,各位前辈们,帮忙分析一下我的错误吧。。。。

  • 写回答

10条回答

  • hatlonely 2015-07-21 15:02
    关注

    用模板类的实现应该写在.h里面,最好是将.h命名成.hpp,你看看boost里面的头文件基本都是.hpp
    这个其实是因为模板在编译的时候并没有实例化,看下这个文章吧c++模板类(一)理解编译器的编译模板过程

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?