Files
XCEngine/docs/api/core/smartptr/smartptr.md

67 lines
1.8 KiB
Markdown
Raw Normal View History

# SmartPtr
**命名空间**: `XCEngine::Core`
**类型**: `header-only`
2026-03-20 02:35:07 +08:00
**头文件**: `XCEngine/Core/SmartPtr.h`
**描述**: 智能指针类型别名和工厂函数,提供 `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>` | 创建独占指针 |
## 公共方法
| 方法 | 描述 |
|------|------|
| [`Ref`](Ref.md) | `std::shared_ptr<T>` 类型别名 |
| [`UniqueRef`](UniqueRef.md) | `std::unique_ptr<T>` 类型别名 |
| [`MakeRef`](MakeRef.md) | 创建共享指针的工厂函数 |
| [`MakeUnique`](MakeUnique.md) | 创建独占指针的工厂函数 |
## 使用示例
```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);
```
## 相关文档
- [Core 模块总览](../core.md) - 返回模块总览
- [RefCounted](../refcounted/refcounted.md) - 引用计数基类
- [Types](../types/types.md) - 类型别名