프로그래밍 공부/modern C++

스마트 포인터 weak_ptr

재우이 2022. 2. 17. 00:21

3. weak_ptr

- weak_ptr은 shared_ptr의 참조자이다.

- 하나 이상의 shared_ptr를 참조한다.

- use_count를 증가, 감소 시키지않는다.

(weak reference count 증가 -> 객체 소멸에 관여하지않음)

(string reference count 증가하지않음 -> 객체 소명에 관여)

- shared_ptr 순환 참조 문제를 해결하기 위해 사용

 

*순환 참조(circular reference) 문제

서로가 서로를 가르키는 shared_ptr은 reference count가 0이 될 수가 없어

메모리가 해제되지않는 문제

 

사용법

#include<memory> 추가

weak_ptr<객체> 스마트 포인터 명 = shard_ptr객체;

 

총 코드

#include<iostream>
#include<memory>
#include<string>
using namespace std;

class Person
{
	string name;
	int age;
public:
	Person(const string& name, int age);
	~Person();
	void ShowData();
};

Person::Person(const string& name, int age)
{
	this->age = age;
	this->name = name;
	cout << "Person 생성자 생성" << endl;
}

Person::~Person()
{
	cout << "Person 소멸자 생성" << endl;
}

void Person::ShowData()
{
	cout << "나이 : " << age << endl;
	cout << "이름 : " << name << endl;
}

int main()
{
		shared_ptr<Person> Lee(new Person("JaeWoo", 31));
		Lee->ShowData();
		cout << "reference count : " << Lee.use_count() << endl;
	
		weak_ptr<Person> Lee2 = Lee;
		cout << "reference count : " << Lee.use_count() << endl;

		auto sharedLee(Lee);
		cout << "reference count : " << Lee.use_count() << endl;

		Lee2.reset();
		cout << "reference count : " << Lee.use_count() << endl;

}