boost::shared_ptr指针设置NULL的方法

 在使用boost::shared_ptr的时候,有时候想将指针置为NULL。一般地,我们可以向传统指针那样,直接将NULL赋值给指针,也可以调用boos::shared_ptr的reset()方法,将指针重置,也就是设置为NULL,下面是具体的测试代码:

/*
 * @,@Author: ,: your name
 * @,@Date: ,: 2020-12-09 09:25:03
 * @,@LastEditTime: ,: 2020-12-29 10:28:01
 * @,@LastEditors: ,: Please set LastEditors
 * @,@Description: ,: In User Settings Edit
 * @,@FilePath: ,: /pluginManagerFramework/home/ok/test/f.cpp
 */
#include <iostream>
#include <map>
#include <boost/shared_ptr.hpp>
using namespace std;

class Test
{
  int a;

public:
  Test(int b)
  {
    setA(b);
  }
  void setA(int b)
  {
    a = b;
  }
  int getA()
  {
    return a;
  }
};

int main()
{
  boost::shared_ptr<Test> tptr;
  tptr.reset(new Test(1));

  if (tptr == NULL)
  {
    cout << "tptr is null" << endl;
  }
  else
  {
    cout << "tptr is not null" << endl;
  }
  cout << "begin to reset();" << endl;

  tptr.reset();

  if (tptr == NULL)
  {
    cout << "tptr is null" << endl;
  }
  else
  {
    cout << "tptr is not null" << endl;
  }

  tptr.reset(new Test(2020));

  if (tptr == NULL)
  {
    cout << "tptr is null" << endl;
  }
  else
  {
    cout << "tptr is not null" << endl;
  }

  cout << "set tptr =NULL" << endl;
  
  tptr = NULL;
  if (tptr == NULL)
  {
    cout << "tptr is null" << endl;
  }
  else
  {
    cout << "tptr is not null" << endl;
  }
  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值