C++11 智能指针——shared_ptr

shared_ptr是C++11中最智能的指针,它使用引用计数,当使用一个shared_ptr构造或赋值给另外一个shared_ptr时,
引用计数+1.当一个shared_ptr销毁时引用计数-1,直到引用计数为0时,delete掉申请的资源。

问题:
1.关于shared_ptr()构造:shared_ptr<int> ipNull();这里的ipNUll会被解释为function,不可以作为左值
使用。如果要声明一个原始指针为null且引用计数为0的shared_ptr应该使用:shared_ptr<int> ipNull;
2.shared_ptr不可交叉引用,若要交叉引用,则应该使用weak_ptr

—————————————————————————

shared_ptr的简单使用

#include <iostream>
#include <memory>
#include <cstdio>

using namespace std;

int main()
{
    //*<constructor:>*//
    shared_ptr<int> sipnull();              //create a shared_ptr,but it manager a nullptr and it's reference-count is zero
    shared_ptr<int> sip(new int(13));       //create a new obj,it's reference-count is one
    shared_ptr<int> sip1(sip);              //cause reference-count increase to two

    sipnull.reset(new int(12));         //ERROR:".reset"的左边必须有类/结构/联合...
    //sipnull = sip;                        //ERROR:C2659,此错误是编译器将左边变量类型解释为函数造成的
    //正确的用法是:shared_ptr<int> sipnull;
    cout << "sip and sip1 reference-count is:"
         << sip.use_count() << endl;        //cout :"sip and sip1 reference-count is:2"

    cout << "sip & sip1 is not null?" << boolalpha << sip.operator bool() << endl;
    //"sip & sip1 is not null?true"

    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值