2021-04-08 09:51:13 +08:00

112 lines
1.8 KiB
C++

#include "precompile.h"
#include "weakptr.h"
#include "creature.h"
CreatureWeakPtrChunk::CreatureWeakPtrChunk()
{
INIT_LIST_HEAD(&ptrs_);
}
CreatureWeakPtrChunk::~CreatureWeakPtrChunk()
{
Clear();
}
void CreatureWeakPtrChunk::Clear()
{
struct CreatureWeakPtr *weakptr, *tmp;
struct list_head ptr_list;
list_replace_init(&ptrs_, &ptr_list);
list_for_each_entry_safe(weakptr, tmp, &ptr_list, entry_) {
weakptr->Reset();
}
}
void CreatureWeakPtrChunk::Set(Creature* c)
{
ptr_ = c;
}
CreatureWeakPtr::CreatureWeakPtr()
{
INIT_LIST_HEAD(&entry_);
}
CreatureWeakPtr::CreatureWeakPtr(const CreatureWeakPtr& x)
{
INIT_LIST_HEAD(&entry_);
if (x.ptr_) {
Attach(x.ptr_);
}
}
CreatureWeakPtr::CreatureWeakPtr(CreatureWeakPtr&& x)
{
INIT_LIST_HEAD(&entry_);
if (x.ptr_) {
Attach(x.ptr_);
x.Detach();
}
}
CreatureWeakPtr& CreatureWeakPtr::operator=(const CreatureWeakPtr& x)
{
if (ptr_) {
Detach();
}
if (x.ptr_) {
Attach(x.ptr_);
}
return *this;
}
CreatureWeakPtr&& CreatureWeakPtr::operator=(CreatureWeakPtr&& x)
{
if (ptr_) {
Detach();
}
if (x.ptr_) {
Attach(x.ptr_);
x.Detach();
}
abort();
// return *this;
}
CreatureWeakPtr::~CreatureWeakPtr()
{
Reset();
}
void CreatureWeakPtr::Reset()
{
if (ptr_) {
Detach();
}
}
Creature* CreatureWeakPtr::Get()
{
return ptr_;
}
void CreatureWeakPtr::Attach(Creature* c)
{
Reset();
CreatureWeakPtrChunk* chunk = c->GetWeakPtrChunk();
if (c != chunk->ptr_) {
abort();
}
ptr_ = c;
list_add_tail(&entry_, &chunk->ptrs_);
}
void CreatureWeakPtr::Detach()
{
if (ptr_) {
ptr_ = nullptr;
list_del_init(&entry_);
}
}