Effective C++ .13使用智能指针来引用资源

#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 driven() {
    shared_ptr<Kiwi> p(new Kiwi(100));
    cout<<p->getWeight()<<endl;

    shared_ptr<Kiwi> q = p;
    cout<<p->getWeight()<<endl;
    cout<<q->getWeight()<<endl;

}

int main() {
    cout<<"test start"<<endl;
    driven();
    cout<<"test end"<<endl;
    return 0;
}

auto_ptr同时只能有一个指向资源

shared_ptr同时可以有多个指向资源

posted @ 2014-12-21 20:33  卖程序的小歪  阅读(155)  评论(0编辑  收藏  举报