您的位置:首页 > 其它

条款18 让接口容易使用,不易被误用

2016-12-20 02:28 176 查看
这一节主要要告诉c++使用者,怎么对待接口(包括function 接口,class接口,template接口);

应该在设计接口的时候,就应考虑它的易用性,减少出错的可能。

考虑函数struct Foo* test();怎么使用智能指针减少资源泄漏的风险?

1,使用shared_ptr作为指针返回值类型

2,使用对象的特定删除器,对于互斥锁(mutex)的解除同样适用

#include <iostream>
#include <algorithm>
#include <memory>
#include <vector>

//using namespace std;
class Foo{
public:
Foo(){
std::cout<<"ctor..\n";
}
~Foo(){
std::cout<<"dtor..\n";
}
};

///对shared_ptr使用删除器
void deleteFoo(Foo *f){
std::cout<<"delete from delteFoo\n";
delete f;
}

std::shared_ptr<Foo> test(){
Foo *fp = new Foo();
std::shared_ptr<Foo> sh1(fp,deleteFoo);
return sh1;
}

int main() {
std::shared_ptr<Foo> re = test();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: