【C++】强弱智能指针引起的线程安全问题

智能指针解决裸指针问题
本文通过对比裸指针和智能指针的使用,展示了如何利用shared_ptr和weak_ptr来避免裸指针带来的不安全性。通过示例代码演示了在多线程环境下,智能指针能够确保对象在被引用时仍然有效。

使用普通裸指针造成的问题

#include <iostream>
#include <memory>
#include <thread>
using namespace std;
class A
{
public:
	A() { cout << "A()" << endl; }
	~A() { cout << "~A()" << endl; }
	void funA()
	{
		cout << "A的一个非常好用的一个方法" << endl;
	}
};
void hander01(A *p)
{
    std::this_thread::sleep_for(std::chrono::seconds(2));
    p->funA();
}
int main()
{
    A *p = new A();
    thread t1(hander01,p);
    delete p;
    t1.join();
}

运行结果:

A在析构完成之后还可以调用A的方法,这个操作是极其不安全的一个操作的,所以我们可以使用强弱智能指针来使得操作变得安全起来。

shared_ptr 和 weak_ptr的解决问题

#include <iostream>
#include <memory>
#include <thread>
using namespace std;
class A
{
public:
	A() { cout << "A()" << endl; }
	~A() { cout << "~A()" << endl; }
	void funA()
	{
		cout << "A的一个非常好用的一个方法" << endl;
	}
};
void handler01(weak_ptr<A> q)
{
	//需要检测对象A是否存活
	std::this_thread::sleep_for(std::chrono::seconds(2));
	shared_ptr<A> ptmp = q.lock();
	if (ptmp != nullptr)
	{
		ptmp->funA();
	}
	else
	{
		cout << "A对象已经析构" << endl;
	}
	
}
int main()
{
	{
		shared_ptr<A> p(new A());
		thread t1(handler01, weak_ptr<A>(p));
		t1.detach();
	}
	std::this_thread::sleep_for(std::chrono::seconds(10));
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值