scoped_ptr
不能被復制或賦值給其他 scoped_ptr
對象,不能與其他指針比較 (除了 nullptr)
scoped_ptr 用例
template <typename T>
class scoped_ptr {
public:// 構造函數:初始化 scoped_ptr 并接管指針的所有權explicit scoped_ptr(T* ptr = nullptr) : ptr_(ptr) {}// 析構函數:釋放管理的對象~scoped_ptr() {delete ptr_;}// 禁止復制構造函數和賦值操作符scoped_ptr(const scoped_ptr&) = delete;scoped_ptr& operator=(const scoped_ptr&) = delete;// 移動構造函數和移動賦值操作符scoped_ptr(scoped_ptr&& other) noexcept : ptr_(other.release()) {}scoped_ptr& operator=(scoped_ptr&& other) noexcept {if (this != &other) {reset(other.release());}return *this;}// 重載解引用操作符T& operator*() const {return *ptr_;}// 重載箭頭操作符T* operator->() const {return ptr_;}// 獲取管理的指針T* get() const {return ptr_;}// 釋放管理的指針并返回T* release() {T* tmp = ptr_;ptr_ = nullptr;return tmp;}// 重置管理的指針void reset(T* ptr = nullptr) {if (ptr_ != ptr) {delete ptr_;ptr_ = ptr;}}// 檢查是否管理一個非空指針explicit operator bool() const {return ptr_ != nullptr;}private:T* ptr_;
};
unique_ptr
頭文件<boost/smart_ptr/make_unique.hpp>里實現了make_unique()函數,位于名字空間 boost 而不是 std,為了避免潛在的沖突。
unique_ptr 用例
創建單個對象
#include <memory>struct MyClass {MyClass(int x, double y) : x_(x), y_(y) {}int x_;double y_;
};int main() {auto ptr = std::make_unique<MyClass>(42, 3.14);// ptr is a std::unique_ptr<MyClass>return 0;
}
創建數組
#include <memory>int main() {auto arr = std::make_unique<int[]>(10);// arr is a std::unique_ptr<int[]> with 10 elementsreturn 0;
}
函數中返回動態分配的對象
#include <memory>std::unique_ptr<int> createInt(int value) {</