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

标签 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)'

显然,非模板化的等效项工作得很好。

最佳答案

B 私有(private)地继承自 A,因此不存在从 BA 的可用转换。更改为 public 继承,您的代码将可以编译。

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

在您的示例中,A 的析构函数应该是virtual,否则您将拥有 undefined behaviorfoo 超出范围时,因为您将尝试通过 A * 删除 B 实例。

关于c++ - 在 C++1y 中从模板化基派生的类型上对 unique_ptr 使用 std::move,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092009/

相关文章:

c++ - 使用 vector 的 merge_sort 适用于少于 9 个输入

c++ - 使用 boost strand 和 std::mutex

c++ - 从文件 C++ 访问对象时出现读取访问冲突。

c++ - 如何在 C++ 中使用 std::function 访问 Functor 的成员函数?

gcc - 用于 MinGW w64 的 OpenMP?

c++ - 分而治之是否总能获得更好的表现?

c++ - Qt 在 QTextBrowser 中的 QVector<T>::operator[]: "index out of range"中抛出 ASSERT 失败

python - MinGW 对 `_imp__PyExc_TypeError' 的 undefined reference

c - 当我从文件中读取时打印出意想不到的结果

c++ - Visual Studio 2010下的Socket编程,非托管C++