unique_ptr 的简单实现
作者:互联网
template <typename T> class poor_unique_ptr { public: explicit poor_unique_ptr(T* ptr=nullptr): ptr_(ptr) {}; ~poor_unique_ptr() { if (ptr_) { delete ptr_; } } // 删除拷贝构造和拷贝赋值 poor_unique_ptr(const poor_unique_ptr&) = delete; poor_unique_ptr& operator=(const poor_unique_ptr&) = delete; // 移动拷贝和移动赋值 poor_unique_ptr(poor_unique_ptr&& rhs): ptr_{rhs.release()} {} poor_unique_ptr& operator=(poor_unique_ptr&& rhs) { reset(rhs.release()); return *this; } T* get() const {return ptr_;} T* release() { // 并不会释放其指向的对象 T *p = ptr_; ptr_ = nullptr; return p; } void reset(T* ptr) { delete ptr_; ptr_ = ptr; } void swap(poor_unique_ptr& rhs){ std::swap(ptr_, rhs.ptr_); } T& operator*() {return *ptr_;} T* operator->() {return ptr_;} explicit operator bool() {return static_cast<bool>(ptr_);} private: T* ptr_; };
标签:poor,return,rhs,简单,operator,unique,ptr 来源: https://www.cnblogs.com/zyb993963526/p/16402100.html