cxx笔记09-cxx11智能指针

c++11智能指针的应用

shared_ptr

共享的智能指针

make_shared

weak_ptr

弱引用的智能指针,它不共享指针,不能操作资源,是用来监视shared_ptr的。

class item
{
private:
    std::string _name;
    float _price;
public:
    item(const string &name,float price):_name(name),_price(price){}
    ~item(){cout<<"hello delete item.";<<endl;
    float getPrice() const {return _price;}
    void setPrice(float price) {_price=price;}
    item* clone() const {return new item(*this);}
};

class A
{
public:
    A(const shared_ptr<item>& obj):_obj(obj){}
    ~A(){printf("DELETE A\n");}
    const shared_ptr<item>& get() const {return _obj;}
private:
    shared_ptr<item> _obj;
}

int main()
{
    {
        shared_ptr<item> item1(new item("hello",20));
        cout<<item1.use_count()<<endl;
        cout<<itme1->getPrice()<<endl;
        {
            A a(item1);
            cout<<item1.use_cout()<<endl;
            
            a.get()->setPrice(30);
            cout<<item1->getPrice()<<end;
            
            A b(a);
            cout<<item.use_count()<<endl;
            b.get()->setprice(50);
            cout<<b.get()->getprice()<<endl;
        }
        cout<<item1.use_count()<<endl;
    }
    int *p=new int(30);
    shared_ptr<int> sp1(p);
    shared_ptr<int> sp2=make_shared<int>(20);
    shared_ptr<int> sp3(sp2);
    shared_ptr<int> sp4=(new int(20));
    cout<<"sp2:"<<sp2.use_count()<<" value:"<<*sp2<<endl;
    cout<<"sp1:"<<sp1.use_count()<<" value:"<<*sp1<<endl;
    cout<<"sp3:"<<sp3.use_count()<<" value:"<<*sp3<<endl;
}

unique_ptr

unique_ptr 不共享它的指针。它无法复制到其他 unique_ptr,无法通过值传递到函数,也无法用于需要副本的任何标准模板库 (STL) 算法。只能移动unique_ptr。这意味着,内存资源所有权将转移到另一 unique_ptr,并且原始 unique_ptr 不再拥有此资源。我们建议你将对象限制为由一个所有者所有,因为多个所有权会使程序逻辑变得复杂。因此,当需要智能指针用于纯 C++ 对象时,可使用 unique_ptr,而当构造 unique_ptr 时,可使用make_unique Helper 函数。

std::unique_ptr实现了独享所有权的语义。一个非空的std::unique_ptr总是拥有它所指向的资源。转移一个std::unique_ptr将会把所有权也从源指针转移给目标指针(源指针被置空)。拷贝一个std::unique_ptr将不被允许,因为如果你拷贝一个std::unique_ptr,那么拷贝结束后,这两个std::unique_ptr都会指向相同的资源,它们都认为自己拥有这块资源(所以都会企图释放)。因此std::unique_ptr是一个仅能移动(move_only)的类型。当指针析构时,它所拥有的资源也被销毁。默认情况下,资源的析构是伴随着调用std::unique_ptr内部的原始指针的delete操作的。

下图演示了两个 unique_ptr 实例之间的所有权转换。

posted @ 2024-06-30 17:23  alvinlyb  阅读(1)  评论(0编辑  收藏  举报