共享指针,弱指针

#include
#include

using namespace std;

class Child;
class Parent;

class A
{
	public:
		int m_num;

		A()
		{
			cout << "A" << endl;	
		}
		
		A(int num) : m_num(num)
		{
			cout << "A int" << endl;
		}
		
		~A()
		{
			cout << "~A" << endl;
		}	
};

class Parent
{
	public:
		Parent()
		{
			cout << "Parent" << endl;
		}

		~Parent()
		{
			cout << "~Parent" << endl;
		}
		
		shared_ptr<Child> c;
};

class Child
{
	public:
		Child()
		{
			cout << "child" << endl;
		}

		~Child()
		{
			cout << "~child" << endl;
		}

		shared_ptr<Parent> p;
};
			
int main()
{
#if 0
	//weak_ptr:类模板,弱指针(弱引用计数)
	//特点:不影响对象的生命周期,对象释放时不关心有多少弱指针指向该对象
	//初始化:辅助shared_ptr,可以使弱指针指向一个共享指针(共享指针赋值给弱指针),但是不能把弱指针赋值给共享指针
	//弱指针不能指向一个新的空间;

	shared_ptr<A> pa(new A(5));
	weak_ptr<A> wpa = pa;
	weak_ptr<A> wpa2 = pa;
	weak_ptr<A> wpa3 = pa;

	//weak_ptr常用功能:
	//lock():获取弱指针指向的对象所对应的共享指针,如果指向的对象释放,那么返回nullptr;(将弱指针转换为共享指针)
	//pa.reset();
	auto pb = wpa.lock();
	if(pb == nullptr)
	{
		cout << "pb is nullptr" << endl;
	}
	
	//reset():弱引用计数-1
	wpa.reset();

	//use_count()返回的是shared_ptr的引用计数
	cout << "wpa.use_count = " << wpa.use_count() << endl;
	
	//expired():判断当前弱指针指向的对象是否被释放
	//若被释放返回true,否则返回false
	if(wpa.expired())
	{
		cout << "wpa point class is free!" << endl;
	}
#endif

	shared_ptr<Parent> pp(new Parent());
	shared_ptr<Child> cc(new Child());

	//循环引用
	pp->c = cc;
	cc->p = pp;
	
	cout << "hello world!" << endl;

	return 0;
}

你可能感兴趣的:(嵌入式面向对象编程)