Server/C++

class 자신을 참조하는 shared_ptr

Juzdalua 2024. 8. 13. 23:45

포인터 자체를 shared_ptr로 캐스팅하면 안된다.

공유포인터로 캐스팅하는게 아닌, 해당 포인터를 가르키는 shared_ptr을 새로 생성하는 것이다.

class A 
{
};

class B
{
public:
	shared_ptr<A> owner;
};

class C : public A
{
public:
	void SetC()
	{
		B* b = new B();

		b->owner = shared_ptr<A>(this); // shared_ptr 중복

		delete b;
	}
};

 


enable_shared_from_this

enable_shared_from_this 템플릿을 상속 받으면 자신을 가르키는 weak_ptr을 멤버변수로 상속 받는다.

class A : public enable_shared_from_this<A>
{
	// weak_ptr<A> _Wptr;
};

 

해당 템플릿과 shared_from_this() 함수를 이용하면, 레퍼런스 카운트를 유지한 채로 자기 자신에 대한 shared_ptr을 만들 수 있다.

class A : public enable_shared_from_this<A>
{
};

class B
{
public:
	shared_ptr<A> owner;
};

class C : public A
{
public:
	void SetC()
	{
		B* b = new B();

		b->owner = shared_from_this();

		delete b;
	}
};

 

주의사항)

bad_weak_ptr 에러

shared_from_this() 함수를 사용하여 weak_ptr을 사용한 클래스 C는 앞으로 shared_ptr로만 사용해야한다.

int main()
{
    A* a = new A();

    B* b = new B();

    C* c = new C();
    c->SetC(); // Error

    shared_ptr<C> cc = make_shared<C>();
    cc->SetC(); // OK

    delete a;
    delete b;
    delete c;

    return 0;
}

 

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

WSASend에서 Scatter-Gather 기법 사용하기  (0) 2024.08.16
WSARecv에서 순환버퍼의 사용  (0) 2024.08.16
IOCP Completion Port 모델  (0) 2024.08.13
Overlapped 모델  (0) 2024.08.13
Blocking & Synchronous  (1) 2024.08.12