首页 > 代码库 > Effective C++ .14 智能指针的拷贝与deleter函数
Effective C++ .14 智能指针的拷贝与deleter函数
#include <iostream>#include <cstdlib>#include <memory>using namespace std;class Kiwi {private: int weight;public: Kiwi(int w) : weight(w) {} ~Kiwi() { cout<<"~Kiwi"<<endl; } int getWeight() {return weight;}};void deleter(Kiwi* x) { cout<<"deleting"<<endl; // if remove below line object will not be delete by smart pointer delete x;}void driven() { shared_ptr<Kiwi> p(new Kiwi(100), deleter); cout<<p->getWeight()<<endl; cout<<p.use_count()<<endl; shared_ptr<Kiwi> q = p; cout<<p->getWeight()<<endl; cout<<q->getWeight()<<endl; cout<<p.use_count()<<endl; cout<<q.use_count()<<endl;}int main() { cout<<"test start"<<endl; driven(); cout<<"test end"<<endl; return 0;}
智能可以定义deleter函数,即在其认为资源应该释放时调用该函数来代替默认的delete操作
Effective C++ .14 智能指针的拷贝与deleter函数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。