ShitEngine
基于 C++20 与 SDL3 的轻量级 2D 游戏引擎
载入中...
搜索中...
未找到
WeakComponentRef< T > 模板类 参考

组件弱引用 更多...

#include <GameObject.h>

Public 成员函数

 WeakComponentRef ()=default
 WeakComponentRef (GameObject *owner, const std::weak_ptr< void > &lifetime)
T * get () const
 获取组件(组件已移除或对象已销毁则返回 nullptr)
bool valid () const
 组件当前是否有效(onAttach 后、removeComponent 前,且 owner 未被销毁)
T * operator-> () const
 便捷解引用(调用前建议先 valid() 检查或直接解引用判空)
 operator bool () const
GameObjectgetOwner () const
 获取所属 GameObject(可能已被销毁,调用方需自行保证安全)

详细描述

template<typename T>
class Shit::WeakComponentRef< T >

组件弱引用

安全持有组件引用而不导致悬垂:不存组件指针,只存 owner + 生命周期令牌 + 模板类型, 访问时通过 owner->getComponent<T>() 现查。组件被 removeComponent 移除、或所属 GameObject 被销毁后,get() 返回 nullptr(逻辑已死可检测),不会 use-after-free。

用法: auto ref = go->getWeakRef<Shit::UIText>(); button->setOnClick([ref]() { if (Shit::UIText* t = ref.get()) t->setText("..."); // 已移除则安全跳过 });

注意:这是"弱引用"不是"强引用"——不能阻止组件销毁,也不延长其生命周期。 若组件必须长期存活,属于生命周期设计问题而非引用问题。

构造及析构函数说明

◆ WeakComponentRef() [1/2]

template<typename T>
WeakComponentRef ( )
default

◆ WeakComponentRef() [2/2]

template<typename T>
WeakComponentRef ( GameObject * owner,
const std::weak_ptr< void > & lifetime )
inlineexplicit

成员函数说明

◆ get()

template<typename T>
T * get ( ) const
inline

获取组件(组件已移除或对象已销毁则返回 nullptr)

◆ getOwner()

template<typename T>
GameObject * getOwner ( ) const
inline

获取所属 GameObject(可能已被销毁,调用方需自行保证安全)

◆ operator bool()

template<typename T>
operator bool ( ) const
inlineexplicit

◆ operator->()

template<typename T>
T * operator-> ( ) const
inline

便捷解引用(调用前建议先 valid() 检查或直接解引用判空)

◆ valid()

template<typename T>
bool valid ( ) const
inline

组件当前是否有效(onAttach 后、removeComponent 前,且 owner 未被销毁)


该类的文档由以下文件生成: