如果我要自己写,我想我会做些类似的事情:

template<typename T, typename Dtor = std::default_delete<T> >
class Uptr : private Dtor {
  T* vl_;
public:
  explicit Uptr(T* vl = nullptr) noexcept : vl_(vl) {}
  ~Uptr() noexcept { Dtor::operator()(vl_); }

  Uptr& swap(Uptr& o) noexcept { T* tmp; tmp = vl_; vl_=o.vl_; o.vl_ = tmp; }

  Uptr& operator=(Uptr&& o) noexcept { o.swap(*this); }
  Uptr& operator=(nullptr_t) noexcept { vl_=nullptr; return *this; }
  Uptr(Uptr&& o) noexcept : Uptr(nullptr) { *this = std::move(o); }

  Uptr(const Uptr& o) = delete;
  Uptr& operator=(const Uptr& o) = delete;


  operator T*() noexcept { return vl_; }
  operator const T*() const noexcept { return vl_; }

  T* release() noexcept { T* ret = vl_; vl_=nullptr; return ret; }

  const Dtor& deleter() const noexcept { return *(static_cast<Dtor*>(this)); }
  Dtor& deleter() noexcept { return *(static_cast<Dtor*>(this)); }
};

并避免自己定义get()和运算符*->[]

在这种情况下进行隐式转换有什么问题?

最佳答案

我认为您的问题不是特定于unique_ptr,而是一般地询问智能指针。

Herb Sutter wrote about this a long time ago。显然,它将允许您编写逻辑错误的代码,例如:

unique_ptr<something> p;
...
delete p; // p is a smart pointer - probably not what you want.

和其他类似的代码。

09-06 16:55