【C++】Item18. Make interfaces easy to use correctly and hard to use incorrectly
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【C++】Item18. Make interfaces easy to use correctly and hard to use incorrectly,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1151字,纯文字阅读大概需要2分钟。
内容图文
接口容易被正确使用,不易被误用
c++简单工厂模式时,初级实现为ITest* CreateTestOld(), 然后用户负责释放返回的对象。如果忘记释放就会造成memory leak,所以在设计工厂接口时就应屏蔽这个潜在的问题,这时就可以用智能指针shared_ptr<ITest> CreateTest(),由他负责对象资源的管理,而对客户端的使用来说更简洁了。
1 #include "stdafx.h" 2 #include <memory> 3 #include <iostream> 4usingnamespace std; 5 6class ITest 7{ 8public: 9virtualvoid Func() = 0; 10virtual ~ITest(){} 11}; 1213class Test : public ITest 14{ 15public: 16void Func() override17 { 18 cout << "Test::Func" << endl; 19 } 20 Test() 21 { 22 cout << "Test ctor!" << endl; 23 } 24 ~Test() 25 { 26 cout << "Test destroy!" << endl; 27 } 2829}; 3031class Factory 32{ 33public: 34static shared_ptr<ITest> CreateTest() 35 { 36return shared_ptr<ITest>(new Test); 37 } 3839static ITest* CreateTestOld() 40 { 41returnnew Test; 42 } 43}; 444546int _tmain(int argc, _TCHAR* argv[]) 47{ 48 auto ptr2 = Factory::CreateTestOld(); 49 ptr2->Func(); 50 delete ptr2; 5152 auto ptr = Factory::CreateTest(); 53 ptr->Func(); 5455return0; 56 }
原文:http://www.cnblogs.com/neking/p/3527973.html
内容总结
以上是互联网集市为您收集整理的【C++】Item18. Make interfaces easy to use correctly and hard to use incorrectly全部内容,希望文章能够帮你解决【C++】Item18. Make interfaces easy to use correctly and hard to use incorrectly所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。