在C ++ 1y中从模板化基础派生的类型上使用std :: move on unique_ptr

时间:2015-10-12 23:55:00

标签: c++ c++11 gcc c++14 unique-ptr

尝试对从其他类型派生的模板化类型使用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)'

显然,非模板化的等效工作正常。

2 个答案:

答案 0 :(得分:6)

B私下继承自A,因此无法从B转换为A。更改为public继承,您的代码将编译。

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

在您的示例中,A的析构函数应该是virtual,否则当foo超出范围时您将undefined behavior因为您和&#{0}} #39;将通过delete尝试B A *个实例。

答案 1 :(得分:-1)

问题是我正在使用私有继承。 当我将B的定义更改为:     B级:公众 事情正在发挥作用。

我保留其他解决方案仅供记录: 由于缺乏更好的想法,我正在诉诸于此:

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