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

接口容易被正確使用,不易被誤用ios

c++簡單工廠模式時,初級實現爲ITest* CreateTestOld(), 而後用戶負責釋放返回的對象。若是忘記釋放就會形成memory leak,因此在設計工廠接口時就應屏蔽這個潛在的問題,這時就能夠用智能指針shared_ptr<ITest> CreateTest(),由他負責對象資源的管理,而對客戶端的使用來講更簡潔了。c++

 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 }
相關文章
相關標籤/搜索