首页 > 编程语言 > 详细

C++ 自动指针 共享指针

时间:2016-08-26 22:43:24      阅读:197      评论:0      收藏:0      [点我收藏+]
#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;
}

 

C++ 自动指针 共享指针

原文:http://www.cnblogs.com/tangxin-blog/p/5811759.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!