使用std::move在unique_ptr上对c++ 1y中模板化基类派生的类型进行操作

using std::move on unique_ptr on a type derived from templated base in C++1y

本文关键字:派生 基类 类型 操作 1y unique move std ptr 使用 c++      更新时间:2023-10-16

在从另一种类型派生的模板类型上使用std::move语义时,我遇到了问题。也就是说,我在下面的例子中得到了一个错误。

#include <memory>
template <typename T>
class A{
};
template <typename T>
class B:A<T>{
};
int main()
{
  std::unique_ptr<B<int> > bar(new  B<int>());    
  std::unique_ptr<A<int> > foo (std::move(bar));
}

错误在定义foo的那行,它是:

In function 'int main()':
17:47: error: no matching function for call to 'std::unique_ptr<A<int> >::unique_ptr(std::remove_reference<std::unique_ptr<B<int> >&>::type)'

B私下继承A,所以没有从BA的可用转换。修改为public继承,你的代码就可以编译了。

template <typename T>
class B: public A<T>{};
//       ^^^^^^

在您的示例中,A的析构函数应该是virtual,否则当foo超出作用域时,您将有未定义的行为,因为您将试图通过A *delete B实例。

问题是我正在使用私有继承。当我把B的定义改成:乙级:公共一切顺利。

我保留了另一个解决方案只是为了记录:由于没有更好的办法,我只好这样做了:

std::unique_ptr<A<int> > foo ( (A<int> * ) new  B<int>());