unique_ptr/shared_ptr/weak_ptr 선택 기준unique_ptr, 공유가 필요할 때만 shared_ptr” 원칙을 적용할 수 있다.실패하는 코드의 공통점은 같습니다.
그래서 규칙을 먼저 정합니다.
delete (또는 소멸 시 자동 해제)raw 포인터 계약 예시:
Item* item = DropItemRaw(); // 호출자가 우선 소유
if (inventory.AddItem(item)) {
item = nullptr; // 소유권을 인벤토리로 넘김
} else {
delete item; // 추가 실패 시 호출자가 정리
item = nullptr;
}
핵심:
예: 미사일이 Mutalisk* target을 들고 추적 중일 때
target은 댕글링 포인터가 됩니다.대응 전략:
id를 저장하고 매 프레임 안전 조회weak_ptr를 사용해 “존재할 때만 lock해서 사용”중요:
std::unique_ptr<T>: 단일 소유(기본 선택), 참조 카운트 없음std::shared_ptr<T>: 공유 소유(참조 카운트), 정말 공유가 필요할 때만std::weak_ptr<T>: 비소유 관찰자, dangling/순환 참조 완화#include <memory>
std::unique_ptr<Item> DropItem()
{
return std::make_unique<Weapon>();
}
실전 원칙(짧게):
unique_ptrshared_ptrweak_ptr 고려AddItem 실패 시 누가 메모리를 해제해야 하는가?shared_ptr이 아니라 unique_ptr로 두는가?