|
ShitEngine
基于 C++20 与 SDL3 的轻量级 2D 游戏引擎
|
组件弱引用 更多...
#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 | |
| GameObject * | getOwner () const |
| 获取所属 GameObject(可能已被销毁,调用方需自行保证安全) | |
组件弱引用
安全持有组件引用而不导致悬垂:不存组件指针,只存 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("..."); // 已移除则安全跳过 });
注意:这是"弱引用"不是"强引用"——不能阻止组件销毁,也不延长其生命周期。 若组件必须长期存活,属于生命周期设计问题而非引用问题。
|
default |
|
inlineexplicit |
|
inline |
获取组件(组件已移除或对象已销毁则返回 nullptr)
|
inline |
获取所属 GameObject(可能已被销毁,调用方需自行保证安全)
|
inlineexplicit |
|
inline |
便捷解引用(调用前建议先 valid() 检查或直接解引用判空)
|
inline |
组件当前是否有效(onAttach 后、removeComponent 前,且 owner 未被销毁)