FCT
载入中...
搜索中...
未找到
UniquePtr.h
浏览该文件的文档.
1
2#pragma once
3
4#include <type_traits>
5#include <utility>
7#include "RefCount.h"
8
9namespace FCT {
10
23 template<typename T>
24 class UniquePtr {
25 public:
26 // 编译时检查,确保 T 没有继承自 RefCount
27 static_assert(!std::is_base_of<FCT::RefCount, T>::value,
28 "UniquePtr cannot manage types derived from FCT::RefCount. Use a reference-counting pointer instead.");
29
33 UniquePtr() noexcept : m_ptr(nullptr) {}
34
39 explicit UniquePtr(T* ptr) noexcept : m_ptr(ptr) {}
40
45 UniquePtr(UniquePtr&& other) noexcept : m_ptr(other.release()) {}
46
52 UniquePtr& operator=(UniquePtr&& other) noexcept {
53 if (this != &other) {
54 reset(other.release());
55 }
56 return *this;
57 }
58
59 // 禁止拷贝构造和拷贝赋值
60 UniquePtr(const UniquePtr&) = delete;
61 UniquePtr& operator=(const UniquePtr&) = delete;
62
67 reset();
68 }
69
74 T* release() noexcept {
75 T* temp = m_ptr;
76 m_ptr = nullptr;
77 return temp;
78 }
79
84 void reset(T* ptr = nullptr) noexcept {
85 if (m_ptr) {
87 }
88 m_ptr = ptr;
89 }
90
95 T* get() const noexcept {
96 return m_ptr;
97 }
98
103 T& operator*() const {
104 return *m_ptr;
105 }
106
111 T* operator->() const noexcept {
112 return m_ptr;
113 }
114
119 explicit operator bool() const noexcept {
120 return m_ptr != nullptr;
121 }
122
123 private:
125 };
126
136 template<typename T, typename... Args>
137 UniquePtr<T> makeUnique(Args&&... args) {
138 return UniquePtr<T>(FCT_NEW(T, std::forward<Args>(args)...));
139 }
140
141} // namespace FCT
#define FCT_NEW(type,...)
#define FCT_DELETE(args)
一个简单的唯一所有权智能指针。
T * operator->() const noexcept
箭头操作符。
UniquePtr & operator=(UniquePtr &&other) noexcept
移动赋值运算符,从另一个 UniquePtr 转移所有权。
UniquePtr & operator=(const UniquePtr &)=delete
UniquePtr(UniquePtr &&other) noexcept
移动构造函数,从另一个 UniquePtr 转移所有权。
UniquePtr(const UniquePtr &)=delete
void reset(T *ptr=nullptr) noexcept
替换管理的对象。
T * get() const noexcept
获取裸指针。
UniquePtr() noexcept
默认构造函数,创建一个空的 UniquePtr。
~UniquePtr()
析构函数,销毁所管理的对象。
T & operator*() const
解引用操作符。
T * release() noexcept
释放对当前对象的所有权,并返回裸指针。
UniquePtr(T *ptr) noexcept
从裸指针构造 UniquePtr,获得其所有权。
UniquePtr< T > makeUnique(Args &&... args)
创建一个 UniquePtr 的辅助函数,类似于 std::make_unique。