Bootstrap

C++实现unique_ptr

现代C++的说和重要基本思想是RAII(Resource Acquisition Is Initialization). 把资源的生存期交给一个对象管理,在对象析构的时候把负责管理的资源给释放。 C和C++ 比较特殊的一点(但是这却是C/C++之所以强大和高性能的原因之一)是没有Python、Java等的垃圾回收功能,使用malloc和new 申请的内存需要调用对应的free和delete 方法来释放内存,否则将会造成“内存泄露”。基于RAII的思想,C++11推出了智能指针(、 和) , 申请的内存交给智能指针管理,当智能指针的生存期结束,会“智能”的释放掉内存,避免了程序员忘记 delete 造成bug。

这篇不讲解智能指针的用法,而是应该去自己实现 。 注:在实际使用的时候使用标准库的智能指针,而不应该用自己造的,本DIY系列只是为了通过造一些玩具来达到练习的目的。

实现unique_ptr

namespace diy {
template 
class unique_ptr {
 private:
  T *ptr_;

 public:
  explicit unique_ptr(T *ptr) : ptr_(ptr) {}
  unique_ptr(unique_ptr &&other) noexcept : ptr_(nullptr) { this->swap(other); };
  unique_ptr &operator=(unique_ptr &&other) noexcept {
    this->swap(other);
    return *this;
  }
  unique_ptr(const unique_ptr &) = delete;
  unique_ptr &operator=(const unique_ptr &) = delete; 

  ~unique_ptr() {
    delete ptr_;
    ptr_ = nullptr;
  }

  void swap(unique_ptr &other) noexcept {
    using std::swap;
    swap(ptr_, other.ptr_);
  }

  T *get() const { return ptr_; }

  T &operator*() const { return *ptr_; }

  T *operator->() const { return ptr_; }

  // in conditional expression
  explicit operator bool() { return ptr_; }
};
}  // namespace diy

源码和测试用例见

要点

Ref