boost::serialization::singleton单例的使用方式
来源:互联网 发布:c语言编程需要什么软件 编辑:程序博客网 时间:2024/05/17 08:29
#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_const_instance() // const实例int _tmain(int argc, _TCHAR* argv[]){// singleton_ctest obj1;// singleton_ctest obj2;sCTest.Set(10);sCTest_const.Print(); // 10// 操作类的非static成员CDerived cobj;CDerived cobj2;cobj2.Set(89);cobj.Set(10);// 单例的概念:并非是不能定义两个类对象本身// 而是当有多个对象时,通过boost提供的静态成员函数get_mutable_instance()返回实例再调用普通成员函数之后,// 类对象的结果保持一致,就好像类中的所有数据成员都是static一样// 这时的类好像定义了两种同名的数据成员以及成员函数:static与非static// 非static由普通方式调用:即先定义类对象,再调用成员函数// static先调用由boost提供的get_mutable_instance()(或get_const_instance())再调用成员函数的方式// 从而保证单例(因为类的所有成员共享static)// 两种调用互不影响(各自数据成员是分离的),唯一的影响是类现在派生自boost::noncopyable//操作类的“static成员”CDerived::get_mutable_instance().Set(20);CDerived::get_mutable_instance().Print(); // 20// same way:sCDerived.Set(20); sCDerived.Print(); // 20/*sCDerived_const.Set(89); // error*/sCDerived_const.Print(); // 20cobj2.get_mutable_instance().Print(); // 20cobj.get_mutable_instance().Print(); // 20// 操作类的非static成员cobj2.Print(); // 89cobj.Print(); // 10// 实际使用中,我们没有必要也不应该直接定义类对象,而是应该总是通过使用类的static成员函数:// classname::get_mutable_instance().memberFunction(para);(或get_const_instance())来确保“单个实例”// 本例中定义的宏的使用方式与类对象的使用方式相同:name.member_function(para);// 可以将宏当做“对象”return 0;}
0 0
- boost::serialization::singleton单例的使用方式
- boost::serialization::singleton
- 更好的单例(Singleton)实现方式
- Boost的Serialization和SmartPoint搭配使用
- Boost Serialization库使用
- boost中的单例模式(singleton)
- singleton单例模式的使用
- Android - 单例模式(singleton)的使用
- Android - 单例模式(singleton)的使用
- 关于单例(Singleton)模式实现方式的反思
- 单例模式的三种实现方式:singleton
- 单例模式singleton的几种实现方式
- 创建单例模式(Singleton)的几种方式
- 单例模式--Singleton的两种实现方式
- C++ Singleton单例实现方式
- boost的单例
- Singleton Pattern (单例or单件模式)的几种实现方式
- 使用VS2013 实现一个简单的单例模式singleton
- 题目1079:手机键盘
- 第2章 变量和基本类型 课后习题
- linux修改数据库密码
- 【转】DataGridView列的宽度、行的高度自动调整
- 深入浅出.NET接口:阿猫阿狗和程序员
- boost::serialization::singleton单例的使用方式
- win7 跟VC++6.0兼容性处理以及安装程序VA_X_Setup1845 和行号再现
- 日接口日三巨头日时间日三天
- 论程序员如何追女孩
- Android -- Looper.prepare()和Looper.loop()
- hdu 5139 数学+离线暴力求解
- iBatis框架使用 编程4步
- 笔记: 试用Kibana+Logstash+Elasticsearch+Redis
- 关于linux内核无法编译成模块的解决方法