命名空间的定义
头文件mynamespace.h
#ifndef _MY_NAME_SPACE_H_
#define _MY_NAME_SPACE_H_
//定义命名空间
#define _MY_NAME_SPACE_START namespace mynamespace{
#define _MY_NAME_SPACE_END }
#endif
单例
#ifndef _INSTANCE_H_
#define _INSTANCE_H_
#pragma once
#include <mutex>
_MY_NAME_SPACE_START
template<typename T>
class Singleton{
public:
static T& Instance()
{
if (_instance == nullptr)
{
std::lock_guard<std::mutex> lockGuard(myMutex);
if (_instance == nullptr)
{
_instance = new T();
//防止内存泄露
//atexit(Release);
}
}
return *_instance;
}
static T* GetInstance()
{
return _instance;
}
static void Release()
{
Dstroy();
}
private:
Singleton(){};
~Singleton(){};
Singleton(const Singleton&) = delete;
Singleton& operator= (const Singleton&) = delete;
private:
Dstroy()
{
if (_instance != nullptr)
{
delete _instance;
_instance = nullptr;
}
}
std::mutex myMutex;
//禁止重排列
//1.分配内存
//2.调用构造函数
//3.返回指针复制操作
static volatile T* _instance;
};
template<typename T> T* volatile Singleton<T>::_instance = nullptr;
_MY_NAME_SPACE_END
#endif
另一种写法
#ifndef _INSTANCE_H_
#define _INSTANCE_H_
#pragma once
#include <mutex>
#include <memory>
_MY_NAME_SPACE_START
template<typename T> class Singleton2
{
private:
Singleton2(const Singleton2& tmp);
Ssingleton2& operator= (const Singleton2& tmp);
protected:
//可作为一个基类
Singleton2(){}
public:
virtual ~Singleton2(){}
static T& Instance();
protected:
static std::mutex mt;
//使用只能指针管理单例对象
static shared_ptr<T> _instance;
};
template<typename T> T& Singleton2<T>::Instance()
{
if(_instance == nullptr)
{
std::lock_guard<std::mutex> lockGuard(mt);
if(_instance== nullptr)
{
_instance= shared_ptr<T>(new T);
}
}
return *_instance;
}
template<typename T> shared_ptr<T> Singlenton2<T>::_instance;
_MY_NAME_SPACE_END
#endif
C++11 新写法
#ifndef _INSTANCE_H_
#define _INSTANCE_H_
#pragma once
#include <mutex>
#include <memory>
_MY_NAME_SPACE_START
class Singleton3{
private:
Singleton3()
{
}
Single2(const Singleton3&) = delete;
Singleton3& operator=(const Singleton3&) = delete;
public:
static Singleton3& GetInst()
{
static Singleton3 single;
return single;
}
};
_MY_NAME_SPACE_END
#endif