将 unique_ptr<Derived> 转换为 unique_ptr<Base>
Convert unique_ptr<Derived> to unique_ptr<Base>
一个简单的代码
class Base {};
class Derived : Base {};
unique_ptr<Base> Create() {
unique_ptr<Base> basePtr = make_unique<Derived>(); // compile error
return basePtr;
}
产生编译错误 ("no suitable conversion")。我发现 similar question 解决方案是使用 std::move
。我试过这个
unique_ptr<Derived> derived = make_unique<Derived>();
unique_ptr<Base> basePtr = std::move(derived); // compile error
但现在std::move
产生编译错误。我还发现 如果我们使用
,其中(如果我理解得很好的话)转换应该是自动的
unique_ptr<Base> basePtr = make_unique<Derived>(new Derived()); //compile error
但这也行不通(编译错误),而且 将 new
与智能指针一起使用也不是 。
正确的解决方案是什么?
到目前为止我找到的唯一可行的解决方案
unique_ptr<Base> basePtr = unique_ptr<Base>((Base*)new Derived());
长得真丑
您的 class 是从基础 class 私有继承的。这是 class
的默认值,而 struct
的默认值是 public 继承。这使得外部派生到基础的转换无效。 unique_ptr
使用 public 继承(live example)可以很好地处理派生到基础的转换:
class Base {};
class Derived : public Base {};
^^^^^^
如下所述,在使用 unique_ptr
时向基础 class 添加一个虚拟析构函数也很重要,因为多态析构依赖于此来实现明确定义的行为。 shared_ptr
不需要这个,但这已经离题了。
模式在pimpl惯用语中经常使用,所以需要virtual destructor
一个简单的代码
class Base {};
class Derived : Base {};
unique_ptr<Base> Create() {
unique_ptr<Base> basePtr = make_unique<Derived>(); // compile error
return basePtr;
}
产生编译错误 ("no suitable conversion")。我发现 similar question 解决方案是使用 std::move
。我试过这个
unique_ptr<Derived> derived = make_unique<Derived>();
unique_ptr<Base> basePtr = std::move(derived); // compile error
但现在std::move
产生编译错误。我还发现
unique_ptr<Base> basePtr = make_unique<Derived>(new Derived()); //compile error
但这也行不通(编译错误),而且 new
与智能指针一起使用也不是
正确的解决方案是什么?
到目前为止我找到的唯一可行的解决方案
unique_ptr<Base> basePtr = unique_ptr<Base>((Base*)new Derived());
长得真丑
您的 class 是从基础 class 私有继承的。这是 class
的默认值,而 struct
的默认值是 public 继承。这使得外部派生到基础的转换无效。 unique_ptr
使用 public 继承(live example)可以很好地处理派生到基础的转换:
class Base {};
class Derived : public Base {};
^^^^^^
如下所述,在使用 unique_ptr
时向基础 class 添加一个虚拟析构函数也很重要,因为多态析构依赖于此来实现明确定义的行为。 shared_ptr
不需要这个,但这已经离题了。
模式在pimpl惯用语中经常使用,所以需要virtual destructor