如何改进我的习惯unique_ptrclass?我想知道派生 class 可以转换为基础 class

How to improve my custom unique_ptr class? I want to realize that derived class can cast to base class

我自己实现了一个unique_ptr class如下,用来管理另一个class:

namespace mcj {
template <typename CallbackT>
class unique_ptr {
 public:
  unique_ptr(CallbackT* ptr = nullptr) : ptr_(ptr) {
    std::cout << "unique_ptr normal constructor" << std::endl;
  }

  unique_ptr(unique_ptr<CallbackT>&& ptr) {
    if (ptr_) {
      delete ptr_;
      ptr_ = nullptr;
    }
    ptr_ = ptr.release();
    std::cout << "unique_ptr move constructor(unique_ptr<CallbackT>&& ptr)"
              << std::endl;
  }

  unique_ptr<CallbackT>& operator=(unique_ptr<CallbackT>&& ptr) {
    if (ptr_) {
      delete ptr_;
      ptr_ = nullptr;
    }
    ptr_ = ptr.release();
    std::cout << "unique_ptr move operation(=)" << std::endl;
    return *this;
  }

  unique_ptr(const unique_ptr<CallbackT>& other) = delete;
  unique_ptr<CallbackT>& operator=(const unique_ptr<CallbackT>& other) = delete;

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

  CallbackT& operator*() { return *ptr_; }
  CallbackT* operator->() { return ptr_; }
  CallbackT* get() const { return ptr_; };

  CallbackT* release() {
    if (ptr_) {
      CallbackT* temp = ptr_;
      ptr_ = nullptr;
      return temp;
    }
    return ptr_;
  }

 private:
  CallbackT* ptr_;
};
}  // namespace mcj

我这样调用mcj::unique_ptr,A是base base class,B是derived class:

mcj::unique_ptr<A> CastToBase() {
  return mcj::unique_ptr<B>(new B);
}
mcj::unique_ptr<A> h = CastToBase();

但是出现错误:

/Users/chaojie.mo/Documents/test/test/main.cpp:42:10: error: no viable conversion from returned value of type 'unique_ptr' to function return type 'unique_ptr' return mcj::unique_ptr(new B); ^~~~~~~~~~~~~~~~~~~~~~~~~ /Users/chaojie.mo/Documents/test/src/callback_utils.h:11:3: note: candidate constructor not viable: no known conversion from 'mcj::unique_ptr' to 'A ' for 1st argument unique_ptr(CallbackT ptr = nullptr) : ptr_(ptr) { ^ /Users/chaojie.mo/Documents/test/src/callback_utils.h:15:3: note: candidate constructor not viable: no known conversion from 'mcj::unique_ptr' to 'unique_ptr &&' for 1st argument
unique_ptr(unique_ptr&& ptr) { ^ /Users/chaojie.mo/Documents/test/src/callback_utils.h:35:3: note: candidate constructor not viable: no known conversion from 'mcj::unique_ptr' to 'const unique_ptr &' for 1st argument
unique_ptr(const unique_ptr& other) = delete;

有人可以告诉我如何改进 mcj::unique_ptr 以支持派生 class 可以转换为基础 class 吗?

foo<B> 不是 c++ 中 foo<B> 的子类。 Google 'contravariance and covariance in c++ smart pointers',

您将不得不提取投射它的指针并创建一个新的 unique_ptr 到 return