C++

스마트 포인터

Honyack 2024. 3. 12. 15:53

unique_ptr 

-단독으로만 소유권을 가질수 있는 포인터

#include <iostream>
using namespace std;

class Obj
{
public:
	Obj() { cout << "Obj 생성자" << endl; }
	~Obj() { cout << "obj 소멸자" << endl; }
public:
	void Hello() { cout << "Hello world" << endl; }
};

int main()
{
	unique_ptr<Obj> objP1 = make_unique<Obj>();
	
	objP1->Hello();

	unique_ptr<Obj> objP2 = move(objP1);
	//objP1이 가지고 있던 소유권을 objP2로 넘김
	if (objP1)
	{
		objP1->Hello();
	}
	else
	{
		if (objP1 == nullptr)
			cout << "objP1 은 nullptr입니다." << endl;
	}

	if (objP2)
	{
		objP2->Hello();
	}
	return 0;
}

 

 

shared_ptr

-여러개의 포인터가 참조 할수있음 포인터수를 추적해 카운팅하고

참조하는 포인터가 0이 되면 자동 해제됨

#include <iostream>
using namespace std;

class Obj
{
public:
	Obj() { cout << "Obj 생성자" << endl; }
	~Obj() { cout << "obj 소멸자" << endl; }
public:
	void Hello() { cout << "Hello world" << endl; }
};

int main()
{
	shared_ptr<Obj> objP1 = make_shared<Obj>();
	cout << objP1.use_count() << endl;
	
	objP1->Hello();
	{
		shared_ptr<Obj> objP2 = objP1; //주소 복사
		cout << objP1.use_count() << endl;
	}
	
	if (objP1)
	{
		objP1->Hello();
	}
	else
	{
		if (objP1 == nullptr)
			cout << "objP1 은 nullptr입니다." << endl;
	}
	cout << objP1.use_count() << endl;
	return 0;
}

 

weak_ptr

-소유권을 가지지 않으며 reference Count에 영향을 주지않는다.

사용하기전 lock()을 통해 sharedPtr로 변경하는데 (임시접근)

만약 가리키는 객체가 없다면 nullptr을 반환한다.

 

#include <iostream>
using namespace std;

class Obj
{
public:
	Obj() { cout << "Obj 생성자" << endl; }
	~Obj() { cout << "obj 소멸자" << endl; }
public:
	void Hello() { cout << "Hello world" << endl; }
};

int main()
{
	shared_ptr<Obj> objP1 = make_shared<Obj>();
	weak_ptr<Obj> objP2 = objP1; //reference Count 에 영향을 주지않음
	cout << objP1.use_count() << endl;

	//weak_ptr ->sharedPtr 로 변경
	auto sharedPtr = objP2.lock();
	if (sharedPtr)
	{
		cout << objP1.use_count() << endl;
		cout << objP2.use_count() << endl;
	}


	objP1.reset();
	if (objP1 == nullptr)
	{
		cout << "objP1은 nullptr 입니다." << endl;
	}
	cout << objP2.use_count() << endl;


	return 0;
}

'C++' 카테고리의 다른 글

함수 포인터(다양한 방법)  (0) 2024.03.12
04. namespace  (0) 2023.11.17
03. class(상속)  (0) 2023.11.10
02. class(생성자, 소멸자)  (0) 2023.11.10
01. class(class 기본, Get, Set함수)  (0) 2023.11.10