객체를 참조해서 해당 객체를 따라가는 미사일을 구현해보았다.
#include "pch.h"
#include "CorePch.h"
#include "CoreMacro.h"
#include "ThreadManager.h"
#include <iostream>
class Wraith {
public:
int _hp = 150;
int _posX = 0;
int _posY = 0;
};
class Missile {
public:
void SetTarget(Wraith* target) {
_target = target;
}
void Update() {
int posX = _target->_posX;
int posY = _target->_posY;
// TODO: 쫓아간다
}
Wraith* _target = nullptr;
};
int main()
{
Wraith* wraith = new Wraith();
Missile* missile = new Missile();
missile->SetTarget(wraith);
// 레이스가 피격 당함
wraith->_hp = 0;
delete wraith; //-----------> 추적 객체 메모리에서 삭제
while (true) {
if (missile) {
missile->Update();
}
}
delete missile;
}
missile이 wraith 객체의 변수를 참조할 때, 참조하는 객체가 삭제되어도 포인터값을 참조하기 때문에 garbage값을 참조하게 된다.
포인터 객체가 존재할 때, 자신을 참조하는 객체를 나타내는 참조 여부를 알고 있으면 예방이 용이하다.
여기에 스마트 포인터가 주로 사용된다.
스마트포인터를 활용한 레퍼런스 카운팅을 적용해보자.
// RefCounting.h
#pragma once
/*---------------------
RefCountable
---------------------*/
// 최상위 클래스로 객체들이 상속 받아 사용할 수 있게 한다.
class RefCountable
{
public:
RefCountable() : _refCount(1) {}
virtual ~RefCountable() {} // 최상위 클래스 소멸자는 virtual을 사용하여 메모리 누수를 방지한다.
int32 GetRefCount() { return _refCount; }
int32 AddRef() { return ++_refCount; }
int32 ReleaseRef() {
int32 refCount = --_refCount;
if (refCount == 0)
delete this;
return refCount;
}
protected:
atomic<int32> _refCount;
};
// main.cpp
class Wraith: public RefCountable {
public:
int _hp = 150;
int _posX = 0;
int _posY = 0;
};
class Missile : public RefCountable {
public:
void SetTarget(Wraith* target) {
_target = target;
target->AddRef(); // -----> 참조하는 객체 카운트 증가
}
bool Update() {
if (_target == nullptr)
return true;
int posX = _target->_posX;
int posY = _target->_posY;
// TODO: 쫓아간다
if (_target->_hp == 0) {
_target = nullptr;
return true;
}
return false;
}
Wraith* _target = nullptr;
};
위 코드는 싱글스레드 상황에서는 잘 작동할 것이다.
하지만 멀티스레드 환경에서는 직접 포인터객체를 수정하다보면 Atomic 연산이 이루어 지지 않아 정확한 정보가 읽히지 않게된다.
스마트포인터, Shared PTR을 활용하여 개선해보자.
코드)
https://github.com/Juzdalua/Study-Cpp-Server/blob/master/ServerCore/RefCounting.h
Study-Cpp-Server/ServerCore/RefCounting.h at master · Juzdalua/Study-Cpp-Server
Study C++ IOCP. Contribute to Juzdalua/Study-Cpp-Server development by creating an account on GitHub.
github.com
'Server > C++' 카테고리의 다른 글
스마트 포인터 (0) | 2024.08.03 |
---|---|
Shared Pointer의 문제점 (0) | 2024.08.03 |
DeadLock 탐지 (0) | 2024.08.02 |
Reader, Writer Lock (0) | 2024.08.01 |
std::function (0) | 2024.08.01 |