c++智能指针的使用

1. shared_ptr make_shared

shared_ptr 允许多个指针指向同一个对象

unique_ptr 独占所指向的对象

weak_ptr 弱引用

 返回类指针

shared_ptr<Foo> factory(T arg)

{

        return make_shared<Foo>(arg);

}

void func(T arg)

{

        shared_ptr<Foo> p = factory(arg);

}//p离开作用域, 它指向的内存会被自动释放掉

shared_ptr<Foo> use_(T arg)

{

      shared_ptr<Foo> p = factory(arg);

      return p;

}//p离开了作用域, 它指向的内存不会被释放掉, 因为返回了o, 引用计数进行了递增.

2. enable_shared_from_this

若一个类 T 继承 std::enable_shared_from_this<T> ,则会为该类 T 提供成员函数: shared_from_this.当 T 类型对象 t 被一个为名为 pt 的 std::shared_ptr<T> 类对象管理时,调用 T::shared_from_this 成员函数,将会返回一个新的 std::shared_ptr<T> 对象,它与 pt 共享 t 的所有权。

3.智能指针赋值需要注意的地方: 

int  main()
{
     shared_ptr<Test> ptest( new  Test( "123" ));
     shared_ptr<Test> ptest2( new  Test( "456" ));
     cout<<ptest2->getStr()<<endl;
     cout<<ptest2.use_count()<<endl;
     ptest = ptest2; //"456"引用次数加1,“123”销毁
     ptest->print();
     cout<<ptest2.use_count()<<endl; //2
     cout<<ptest.use_count()<<endl; //2
     ptest.reset();
     ptest2.reset(); //此时“456”销毁
     cout<< "done !\n" ;
     return  0;
}

(1)正确, 直接赋值, pt_1 = pt ,pt引用次数+1; pt_1引用计数减一, 如果为0原内存被释放. 

(2)正确, shared_from_this 将会增加引用计数.

(3) 错误, 类里的方法


class Bad
{
public:
	std::shared_ptr<Bad> getptr() {
		return std::shared_ptr<Bad>(this);
	}
	~Bad() { std::cout << "Bad::~Bad() called" << std::endl; }
};

int main()
{
	// 错误, 每个shared_ptr都认为自己是对象仅有的所有者
	std::shared_ptr<Bad> bp1(new Bad());
	std::shared_ptr<Bad> bp2 = bp1->getptr();
}  // 对象将会被删除两次

4. 使用案例

主页面开启一个线程. 

线程对象为(继承 std::enable_shared_from_this<T>), 引用计数为1;

线程对象方法中, shared_from_this一个局部变量. 则线程对象的引用计数为2;

当主页面销毁, 线程引用计数减1, 子线程可以继续自己销毁引用计数减1.

他俩无论谁最后销毁, 就在那个时机释放子线程对象, 不会因为说主线程资源没了. 子线程崩溃的现象. 

//主页面
std::shared_ptr<RtspRecorder> thread(new Thread());
thread.start();
//线程里
run()
{
        std::shared_ptr<RtspRecorder> t = shared_from_this();
        .....
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值