【C++】Item18. Make interfaces easy to use correctly and hard to use incorrectly

本文探讨了C++中简单工厂模式的一种改进方法,通过使用智能指针来管理对象生命周期,有效避免了内存泄漏问题。文章提供了两种创建对象的方法对比,并展示了如何利用智能指针简化客户端代码。

接口容易被正确使用,不易被误用

c++简单工厂模式时,初级实现为ITest* CreateTestOld(), 然后用户负责释放返回的对象。如果忘记释放就会造成memory leak,所以在设计工厂接口时就应屏蔽这个潜在的问题,这时就可以用智能指针shared_ptr<ITest> CreateTest(),由他负责对象资源的管理,而对客户端的使用来说更简洁了。

 1 #include "stdafx.h"
 2 #include <memory>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 class ITest
 7 {
 8 public:
 9     virtual void Func() = 0;
10     virtual ~ITest(){}
11 };
12 
13 class Test : public ITest
14 {
15 public:
16     void Func() override
17     {
18         cout << "Test::Func" << endl;
19     }
20     Test()
21     {
22         cout << "Test ctor!" << endl;
23     }
24     ~Test()
25     {
26         cout << "Test destroy!" << endl;
27     }
28 
29 };
30 
31 class Factory
32 {
33 public:
34     static shared_ptr<ITest> CreateTest()
35     {
36         return shared_ptr<ITest>(new Test);
37     }
38 
39     static ITest* CreateTestOld()
40     {
41         return new Test;
42     }
43 };
44 
45 
46 int _tmain(int argc, _TCHAR* argv[])
47 {
48     auto ptr2 = Factory::CreateTestOld();
49     ptr2->Func();
50     delete ptr2;
51 
52     auto ptr = Factory::CreateTest();
53     ptr->Func();
54 
55     return 0;
56 }

 

转载于:https://www.cnblogs.com/neking/p/3527973.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值