boost::serialization::singleton单例的使用方式

本文介绍了如何使用Boost库中的serialization::singleton模板实现单例模式,分别展示了通过模板参数方式和继承方式创建单例,并通过实例演示了单例的使用,强调了单例模式确保类只有一个实例并提供全局访问点的重要性。
摘要由CSDN通过智能技术生成
#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值