本文通过实例为大家分享了C++使用智能指针实现模板形式的单例类的具体代码,供大家参考,具体内容如下
实现一个模板形式的单例类,对于任意类型的类经过Singleton的处理之后,都能获取一个单例对象,并且可以传递任意参数
并且还使用了智能指针,把生成的单例对象托管给智能指针,从而实现自动回收单例对象的资源
此外,如果需要一个放在静态成员区的对象供其他类使用,又不希望修改原有的类的代码,这时候可以通过该模板套一层壳,形成单例对象。
头文件
template_singleton.hpp
测试文件
test_template_singleton.cc
- #include "template_singleton.hpp"
- #include <stdio.h>
-
- using std::cout;
- using std::endl;
- using std::cin;
-
- void test(){
- shared_ptr<Computer> pc1 = Singleton<Computer>::getInstance("Xiaomi", 6666);
- cout << "pc1: ";
- pc1->show();
-
- shared_ptr<Computer> pc2 = Singleton<Computer>::getInstance("Xiaomi", 6666);
- cout << "pc1: ";
- pc1->show();
- cout << "pc2: ";
- pc2->show();
-
- pc2->reset("Huawei", 8888);
- cout << endl << "after pc2->reset()" << endl;
- cout << "pc1: ";
- pc1->show();
- cout << "pc2: ";
- pc2->show();
- cout << endl;
-
- shared_ptr<Point> pt3 = Singleton<Point>::getInstance(1, 2);
- shared_ptr<Point> pt4 = Singleton<Point>::getInstance(1, 2);
-
- cout << endl << "通过模板,可以生成不同类型的单例对象:" << endl;
- cout << "pt3: ";
- pt3->show();
- cout << "pt4: ";
- pt4->show();
-
- cout << endl << "使用了智能指针,不同对象指向的地址也一样:" << endl;
- printf("&pc1 = %p\n", &pc1);
- printf("&pc2 = %p\n", &pc2);
- printf("&pt3 = %p\n", &pt3);
- printf("&pt4 = %p\n\n", &pt4);
- printf("&(*pc1) = %p\n", &(*pc1));
- printf("&(*pc2) = %p\n", &(*pc2));
- printf("&(*pt3) = %p\n", &(*pt3));
- printf("&(*pt4) = %p\n\n", &(*pt4));
-
- }
-
- int main()
- {
- test();
- return 0;
- }
运行结果
- Computer(const string &, const int &)
- pc1: name: Xiaomi price: 6666
- pc1: name: Xiaomi price: 6666
- pc2: name: Xiaomi price: 6666
-
- after pc2->reset()
- pc1: name: Huawei price: 8888
- pc2: name: Huawei price: 8888
-
- Point(int, int)
-
- # 通过模板,可以生成不同类型的单例对象:
- pt3: (1, 2)
- pt4: (1, 2)
-
- # 使用了智能指针,不同对象指向的地址也一样:
- &pc1 = 0x7ffe83bbd390
- &pc2 = 0x7ffe83bbd3a0
- &pt3 = 0x7ffe83bbd3b0
- &pt4 = 0x7ffe83bbd3c0
-
- &(*pc1) = 0x55b750c7e300
- &(*pc2) = 0x55b750c7e300
- &(*pt3) = 0x55b750c7e360
- &(*pt4) = 0x55b750c7e360
-
- ~Point()
- ~Computer()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。