#include "stdafx.h"
#include <boost/noncopyable.hpp>
#include <boost/serialization/singleton.hpp>
#include <iostream>
// 使用方式1:模板参数方式
class CTest:public boost::noncopyable // 不能复制、赋值
{
public:
void Set(int i){ m_val = i; }
void Print() const{ std::cout<<m_val<<std::endl;}
private:
int m_val;
};
// 使用typedef以及宏来简化使用
typedef boost::serialization::singleton<CTest> singleton_ctest; // 使用模板的方式只允许单个实例
#define sCTest singleton_ctest::get_mutable_instance() // 非const实例
#define sCTest_const singleton_ctest::get_const_instance() // const实例
// 使用方式2:继承方式
class CDerived:public boost::serialization::singleton<CDerived> // 只允许单个实例,不能复制、赋值(基类派生自boost::noncopyable)
{
public:
void Set(int i){ m_val = i; }
void Print() const{ std::cout<<m_val<<std::endl;}
private:
int m_val;
};
#define sCDerived CDerived::get_mutable_instance() // 非const实例
#define sCDerived_const CDerived::get_co
boost::serialization::singleton单例的使用方式
最新推荐文章于 2023-07-18 16:09:29 发布
本文介绍了如何使用Boost库中的serialization::singleton模板实现单例模式,分别展示了通过模板参数方式和继承方式创建单例,并通过实例演示了单例的使用,强调了单例模式确保类只有一个实例并提供全局访问点的重要性。
摘要由CSDN通过智能技术生成