C++ 自动指针 共享指针

#include <iostream>
#include <string>
#include <memory>
class Item
{
public:
    Item(std::string str):name(str){}
    ~Item(){std::cout<< name << " unitialize!" <<std::endl;}
    void dump(){std::cout<< "I'am " << name <<std::endl;}
    static Item *CreateItem(std::string str)
    {
        Item *pItem = new Item(str);
        return pItem;
    }
private:
    std::string name;
};

int main()
{
    Item *pi = Item::CreateItem("common ptr");
    pi->dump();
    delete pi;

    std::auto_ptr<Item> ap1(Item::CreateItem("auto ptr"));
    ap1.get()->dump();
    std::auto_ptr<Item> ap2 = ap1;
    ap2.get()->dump();        // 此时 auto ptr 对象已经不属于 ap1

    std::shared_ptr<Item> sp1(Item::CreateItem("shared ptr"));
    sp1.get()->dump();
    std::shared_ptr<Item> sp2 = sp1;
    sp2.get()->dump();
    return 0;
}

 

posted @ 2016-08-26 21:15  你好阿汤哥  Views(1446)  Comments(0Edit  收藏  举报