C++如何设计只实例化一次的类?
2018-02-25 13:44
281 查看
这是在看侯捷C++视频的时候,他提出的一个问题,称之为单例模式(singleton),有两种实现方式(懒汉与饿汉),还有多线程,使用场景(工厂模式)等等一些相关的东西,更多了解可以去百度一下。在此就简单做一个总结。
方法一共有n个。根据侯老师所言,目前这两种是比较好的实现方式,所以找出来与大家分享一下。一是:
#include<iostream> #include<vector> #include<string> using namespace std; class A{ public: static A& getObject() { return a ; } void set(int t){ temp = t ; } void print(){ cout << "temp == "<< temp << endl ; } //其他成员函数 private: A() = default ; A(const A& rhs); static A a ; int temp ; }; A A::a ; int main(void){ A::getObject().set(666); A::getObject().print(); return 0 ; }
运行结果:
另外还有下面的这种设计模式。相较于上面的,它就是只要用到就实例化出来,不用到就不浪费内存空间。
#include<iostream> #include<vector> #include<string> using namespace std; class A{ public: static A& getObject() { //给外界的唯一接口 static A a ; //staic 离开函数仍然存在 return a ; } void set(int t){ temp = t ; } void print(){ cout << "temp == "<< temp << endl ; } //其他成员函数 private: A() = default ; A(const A& rhs) ; int temp ; }; int main(void){ A::getObject().set(45); //调用形式 A::getObject().print(); return 0 ; }
运行结果:
当然了,使用new实现也是完全可以的。但是我觉得不是很建议。
#include<iostream> #include<vector> #include<string> using namespace std; class A{ public: static A* getObject(); void set(int t){ temp = t ; } void print(){ cout << "temp == "<< temp << endl ; } //其他成员函数 private: A() = default ; A(const A& rhs) ; ~A(){ //析构函数即使在private中还是会自动执行,不用再写public函数 delete delete p_A ; } A& operator=(const A&); //把复制构造函数和=操作符也设为私有,防止被复制 static A *p_A ; int temp ; }; //注意初始化!!! A* A::p_A = new A(); A* A::getObject(){ return p_A; } int main(void){ A* A1 = A::getObject(); A* A2 = A::getObject(); if (A1 == A2) fprintf(stderr,"A1 = A2\n"); A1->set(888); A1->print(); return 0; }
运行结果:
相关文章推荐
- C++中的property库的设计与实现过程(二)——如何为属性指定get_和set_函数?
- 如何给C++设计一个GC
- 关于如何实现程序一天只启动一次的想法(C++实现)
- 设计模式之单例类——如何让一个类只实例化一个对象
- 用c++设计一个类,这个类只能被实例化3次,且不能被继承
- c++功课:如何设计你的第一个程序
- C++如何阻止一个类被实例化
- C/C++ 如何设计框架
- 润乾V4 报表设计时针对数据每7行进行一次分页,少于7行的补齐如何实现呢?
- C++如何设计一个不能继承的类
- C++如何使用fsteam一次读完未知大小的文件
- 使用C++设计一个类,该类最多能被实例化3次且不能被继承
- 【高质量代码】如何写出更高质量的C/C++代码(2):函数设计
- C++只允许实例化一次的类
- 如何解决C++中用eof()多读一次
- C++之类,类的数组,一次实例化多个类的实例。
- 与Erich Gamma的一次谈话(第一部分) - 如何使用设计模式 (zt)
- 如何在Linux下用C/C++语言操作数据库sqlite3(很不错!设计编译链接等很多问题!)
- c++ 设计一个不能被继承的类,但可以实例化
- [C++设计]如何设计支持网络序列化的类