infinipaint/include/Helpers/NetworkingObjects/NetObjWeakPtr.hpp

82 lines
2.7 KiB
C++
Raw Normal View History

2025-12-10 13:06:45 +03:00
#pragma once
#include "NetObjID.hpp"
#include "NetObjManager.hpp"
#include "NetObjOwnerPtr.decl.hpp"
#include "NetObjTemporaryPtr.decl.hpp"
#include <memory>
2025-12-10 13:06:45 +03:00
namespace NetworkingObjects {
template <typename T> class NetObjWeakPtr {
public:
NetObjWeakPtr():
objMan(nullptr),
id({0, 0})
{}
NetObjWeakPtr(const NetObjWeakPtr& other):
objMan(other.objMan),
id(other.id)
{}
NetObjWeakPtr(const NetObjOwnerPtr<T>& other):
2025-12-10 13:06:45 +03:00
objMan(other.objMan),
id(other.id)
{}
NetObjWeakPtr(const NetObjTemporaryPtr<T>& other):
objMan(other.objMan),
id(other.id)
{}
NetObjWeakPtr& operator=(const NetObjOwnerPtr<T>& other) {
objMan = other.objMan;
id = other.id;
2025-12-11 22:41:53 +03:00
return *this;
}
NetObjWeakPtr& operator=(const NetObjTemporaryPtr<T>& other) {
objMan = other.objMan;
id = other.id;
2025-12-11 22:41:53 +03:00
return *this;
}
2025-12-10 13:06:45 +03:00
NetObjWeakPtr& operator=(const NetObjWeakPtr& other) {
objMan = other.objMan;
id = other.id;
2025-12-11 22:41:53 +03:00
return *this;
2025-12-10 13:06:45 +03:00
}
template <typename S> NetObjWeakPtr<S> cast() const {
return NetObjWeakPtr<S>(objMan, id);
}
bool expired() const {
2025-12-26 10:10:19 +03:00
return (!objMan) || (!objMan->objectData.contains(id));
2025-12-10 13:06:45 +03:00
}
NetObjTemporaryPtr<T> lock() const {
if(!objMan)
return NetObjTemporaryPtr<T>();
2025-12-10 13:06:45 +03:00
auto it = objMan->objectData.find(id);
if(it == objMan->objectData.end())
return NetObjTemporaryPtr<T>();
return NetObjTemporaryPtr<T>(objMan, id, static_cast<T*>(it->second.p));
2025-12-10 13:06:45 +03:00
}
void reset() {
objMan = nullptr;
id = NetObjID({0, 0});
}
2025-12-10 13:06:45 +03:00
NetObjManager* get_obj_man() const {
return objMan;
}
NetObjID get_net_id() const {
return id;
}
bool operator!=(const NetObjWeakPtr<T>& rhs) const {
return objMan != rhs.objMan || id != rhs.id;
}
bool operator==(const NetObjWeakPtr<T>& rhs) const {
return objMan == rhs.objMan && id == rhs.id;
}
private:
NetObjWeakPtr(NetObjManager* initObjMan, NetObjID initID):
objMan(initObjMan),
id(initID)
{}
NetObjManager* objMan;
NetObjID id;
};
}