智能指针

本质上并不神秘,其实就是 RAII 资源管理功能的自然展现而已

  1. //基本智能指针类
  2. class shape_wrapper{
  3. public:
  4. explicit shape_wrapper(shape *ptr = nullptr): ptr_(ptr){}
  5. ~shape_wrapper(){
  6. delete ptr_;
  7. }
  8. shape* get() const
  9. {
  10. return ptr_;
  11. }
  12. private:
  13. shape* ptr_;
  14. }

缺点:

  • 这个类只适用于 shape 类
  • 该类对象的行为不够像指针
  • 拷贝该类对象会引发程序行为异常

    更改1:采用类模板

    1. template<typename T>
    2. class smart_ptr{
    3. public:
    4. explicit smart_ptr(T *ptr = nullptr):ptr_(ptr){}
    5. ~smart_ptr(){
    6. delete ptr_;
    7. }
    8. T* get()const{
    9. return ptr_;
    10. }
    11. private:
    12. T* ptr_;
    13. }
    14. //类模板使用
    15. smart_ptr<shape> =====》 shape_wrapper

    缺点:

  • 它不能用 * 运算符解引用

  • 它不能用 -> 运算符指向对象成员
  • 它不能像指针一样用在布尔表达式里

    更改2:增加成员函数

    1. //通过重载符号,使其看起来像指针。
    2. template <typename T>
    3. class smart_ptr {
    4. public:
    5. …
    6. T& operator*() const { return *ptr_; }
    7. T* operator->() const { return ptr_; }
    8. operator bool() const { return ptr_; }
    9. }

    更改3:拷贝构造和赋值

    使用智能指针的目的就是要减少对象的拷贝,在拷贝时转移指针所有权 ```cpp

template class smartptr { … smart_ptr(smart_ptr& other) //移动拷贝构造 { ptr = other.release(); } smartptr& operator=(smart_ptr& rhs) //生成临时对象去交换指针。 { smart_ptr(rhs).swap(this); return this; } … T release() //释放指针的所有权,并返回新的指针 { T ptr = ptr; ptr = nullptr; return ptr; } void swap(smart_ptr& rhs) { using std::swap; swap(ptr, rhs.ptr_); } … };

  1. 在拷贝构造函数中,通过调用 other 的 release 方法来释放它对指针的所有权。在赋值函数中,则通过拷贝构造产生一个临时对象并调用 swap 来交换对指针的所有权。<br />** 赋值分为拷贝构造和交换两步,异常只可能在第一步发生;而第一步如果发生异常的话,this 对象完全不受任何影响。无论拷贝构造成功与否,结果只有赋值成功和赋值没有效果两种状态,而不会发生因为赋值破坏了当前对象这种场景**。
  2. <a name="ijxsX"></a>
  3. ### 更改4:同时提供移动,拷贝构造函数,增加子类往基类指针转换
  4. ```cpp
  5. template <typename T>
  6. class smart_ptr {
  7. …
  8. smart_ptr(smart_ptr&& other) //移动构造函数
  9. {
  10. ptr_ = other.release();
  11. }
  12. smart_ptr& operator=(smart_ptr rhs) //赋值函数 ,不需要生成临时对象
  13. {
  14. rhs.swap(*this);
  15. return *this;
  16. }
  17. …
  18. };

如果提供了移动构造函数而没有手动提供拷贝构造函数,那后者自动被禁用。

//通过模板构造函数的方式,兼容指针类型
  template <typename U>
  smart_ptr(smart_ptr<U>&& other) //不是移动构造函数
  {
    ptr_ = other.release();
  }
  • 这里的模板参数smart_ptr<U<&&是万能引用,既可以引用左值,又可以引用右值,万能引用在【完美转发】中大有用武之地。 因此上面这段代码所表达的是一个构造函数模板,实例化后可能是拷贝构造函数,也可能是移动构造函数。 ——————————————————————————————————— 补充:在函数模板中,如果参数列表是带“&&”的模板参数,那么这个参数的类型不是右值引用,而是万能引用。
  • 如果提供了移动构造函数而没有同步提供拷贝构造函数,则后者被默认删除。但是上面这个例子不算是提供了移动构造函数,所以需要手动标明删除拷贝构造函数。

    引用计数

    unique_ptr 算是一种较为安全的智能指针了。但是,一个对象只能被单个 unique_ptr 所拥有,这显然不能满足所有使用场合的需求。一种常见的情况是,多个智能指针同时拥有一个对象;当它们全部都失效时,这个对象也同时会被删除。这也就是 shared_ptr。
    image.png

    共享计数接口

    class shared_count{
    public:
      shared_count():count_(1){}
      void add_count{
          ++count_;
      }
      long reduce_count{
          return --count_;
      }
      long get_count{
          return count_;
      }
    private:
      long count_;
    }
    

    引用智能指针实现

    ```cpp

template class smartptr { public: explicit smart_ptr(T* ptr = nullptr) : ptr(ptr) { if (ptr) { sharedcount = new sharedcount(); } } ~smart_ptr() { if (ptr && !sharedcount ->reducecount()) { delete ptr; delete sharedcount; } }

private: T ptr_; shared_count sharedcount; };

<a name="AUjPC"></a>
### 更改拷贝,移动构造函数
```cpp

  smart_ptr(const smart_ptr& other)
  {
    ptr_ = other.ptr_;
    if (ptr_) {
      other.shared_count_
        ->add_count();
      shared_count_ =
        other.shared_count_;
    }
  }
//实现指针兼容
  template <typename U>
  smart_ptr(const smart_ptr<U>& other)
  {
    ptr_ = other.ptr_;
    if (ptr_) {
      other.shared_count_
        ->add_count();
      shared_count_ =
        other.shared_count_;
    }
  }
  template <typename U>
  smart_ptr(smart_ptr<U>&& other)
  {
    ptr_ = other.ptr_;
    if (ptr_) {
      shared_count_ =
        other.shared_count_;
      other.ptr_ = nullptr;
    }
  }

问题:模板的各个实例间并不天然就有 friend 关系,因而不能互访私有成员 ptr 和 shared_count。

友元类声明

template <typename U>
friend class smart_ptr;

指针类型转换

** 在构造函数内部进行转换。

完整代码实现


#include <utility>  // std::swap

class shared_count {
public:
  shared_count() noexcept
    : count_(1) {}
  void add_count() noexcept
  {
    ++count_;
  }
  long reduce_count() noexcept
  {
    return --count_;
  }
  long get_count() const noexcept
  {
    return count_;
  }

private:
  long count_;
};

template <typename T>
class smart_ptr {
public:
  template <typename U>
  friend class smart_ptr;

  explicit smart_ptr(T* ptr = nullptr)
    : ptr_(ptr)
  {
    if (ptr) {
      shared_count_ =
        new shared_count();
    }
  }
  ~smart_ptr()
  {
    if (ptr_ &&
      !shared_count_
         ->reduce_count()) {
      delete ptr_;
      delete shared_count_;
    }
  }

  smart_ptr(const smart_ptr& other)
  {
    ptr_ = other.ptr_;
    if (ptr_) {
      other.shared_count_
        ->add_count();
      shared_count_ =
        other.shared_count_;
    }
  }
  template <typename U>
  smart_ptr(const smart_ptr<U>& other) noexcept
  {
    ptr_ = other.ptr_;
    if (ptr_) {
      other.shared_count_->add_count();
      shared_count_ = other.shared_count_;
    }
  }
  template <typename U>
  smart_ptr(smart_ptr<U>&& other) noexcept
  {
    ptr_ = other.ptr_;
    if (ptr_) {
      shared_count_ =
        other.shared_count_;
      other.ptr_ = nullptr;
    }
  }
  template <typename U>
  smart_ptr(const smart_ptr<U>& other,
            T* ptr) noexcept
  {
    ptr_ = ptr;
    if (ptr_) {
      other.shared_count_
        ->add_count();
      shared_count_ =
        other.shared_count_;
    }
  }
  smart_ptr&
  operator=(smart_ptr rhs) noexcept
  {
    rhs.swap(*this);
    return *this;
  }

  T* get() const noexcept
  {
    return ptr_;
  }
  long use_count() const noexcept
  {
    if (ptr_) {
      return shared_count_
        ->get_count();
    } else {
      return 0;
    }
  }
  void swap(smart_ptr& rhs) noexcept
  {
    using std::swap;
    swap(ptr_, rhs.ptr_);
    swap(shared_count_,
         rhs.shared_count_);
  }

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

private:
  T* ptr_;
  shared_count* shared_count_;
};

template <typename T>
void swap(smart_ptr<T>& lhs,
          smart_ptr<T>& rhs) noexcept
{
  lhs.swap(rhs);
}

template <typename T, typename U>
smart_ptr<T> static_pointer_cast(
  const smart_ptr<U>& other) noexcept
{
  T* ptr = static_cast<T*>(other.get());
  return smart_ptr<T>(other, ptr);
}

template <typename T, typename U>
smart_ptr<T> reinterpret_pointer_cast(
  const smart_ptr<U>& other) noexcept
{
  T* ptr = reinterpret_cast<T*>(other.get());
  return smart_ptr<T>(other, ptr);
}

template <typename T, typename U>
smart_ptr<T> const_pointer_cast(
  const smart_ptr<U>& other) noexcept
{
  T* ptr = const_cast<T*>(other.get());
  return smart_ptr<T>(other, ptr);
}

template <typename T, typename U>
smart_ptr<T> dynamic_pointer_cast(
  const smart_ptr<U>& other) noexcept
{
  T* ptr = dynamic_cast<T*>(other.get());
  return smart_ptr<T>(other, ptr);
}