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操作

原文地址:https://www.cnblogs.com/lailailai/p/4177048.html