55 lines
1.4 KiB
Markdown
55 lines
1.4 KiB
Markdown
|
|
# SmartPtr
|
|||
|
|
|
|||
|
|
**命名空间**: `XCEngine::Core`
|
|||
|
|
|
|||
|
|
**类型**: `header-only`
|
|||
|
|
|
|||
|
|
**描述**: 智能指针类型别名和工厂函数,提供 `std::shared_ptr` 和 `std::unique_ptr` 的简化接口。
|
|||
|
|
|
|||
|
|
## 概述
|
|||
|
|
|
|||
|
|
`Core::SmartPtr` 提供了 `std::shared_ptr` 和 `std::unique_ptr` 的类型别名和工厂函数,使智能指针的使用更加简洁。
|
|||
|
|
|
|||
|
|
## 类型别名
|
|||
|
|
|
|||
|
|
| 别名 | 底层类型 | 描述 |
|
|||
|
|
|------|----------|------|
|
|||
|
|
| `Core::Ref<T>` | `std::shared_ptr<T>` | 共享引用智能指针 |
|
|||
|
|
| `Core::UniqueRef<T>` | `std::unique_ptr<T>` | 独占所有权的智能指针 |
|
|||
|
|
|
|||
|
|
## 工厂函数
|
|||
|
|
|
|||
|
|
| 函数 | 返回值 | 描述 |
|
|||
|
|
|------|--------|------|
|
|||
|
|
| `Core::MakeRef<T>(Args&&... args)` | `Ref<T>` | 创建共享指针 |
|
|||
|
|
| `Core::MakeUnique<T>(Args&&... args)` | `UniqueRef<T>` | 创建独占指针 |
|
|||
|
|
|
|||
|
|
## 使用示例
|
|||
|
|
|
|||
|
|
```cpp
|
|||
|
|
#include <XCEngine/Core/Core.h>
|
|||
|
|
|
|||
|
|
// 使用 Ref(共享指针)
|
|||
|
|
Core::Ref<MyClass> ref = Core::MakeRef<MyClass>(arg1, arg2);
|
|||
|
|
|
|||
|
|
// 使用 UniqueRef(独占指针)
|
|||
|
|
Core::UniqueRef<MyClass> unique = Core::MakeUnique<MyClass>();
|
|||
|
|
|
|||
|
|
// 传递所有权
|
|||
|
|
Core::Ref<MyClass> ref2 = ref; // 引用计数 +1
|
|||
|
|
|
|||
|
|
// 检查有效性
|
|||
|
|
if (ref) {
|
|||
|
|
ref->DoSomething();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 自定义删除器
|
|||
|
|
Core::UniqueRef<FILE, decltype(&fclose)>
|
|||
|
|
file(fopen("test.txt", "r"), &fclose);
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 相关文档
|
|||
|
|
|
|||
|
|
- [RefCounted](./core-refcounted.md) - 引用计数基类
|
|||
|
|
- [Types](./core-types.md) - 类型别名
|