使用std :: move传递的C ++ unique_ptr rvalue不起作用

时间:2017-11-01 20:20:46

标签: c++ unique-ptr

error: call to implicitly-deleted copy of 'unique_ptr<Searchable>'                                                                      
unique_ptr<Searchable> current(std::move(searchSpace.top()));

你好,

我试图找出为什么这不编译。搜索空间是优先级队列,我正在尝试将rvalue searchSpace.top()移动到新的当前对象。

奇怪的是,如果我将优先级队列更改为deque:

        unique_ptr<Searchable> current(std::move(Q.front()));

当Q是deque时,这很好。

那么为什么后者不是第一个?

其余的错误消息:

 copy constructor is implicitly deleted because 'unique_ptr<Searchable,
  std::__1::default_delete<Searchable> >' has a user-declared move
  constructor
_LIBCPP_INLINE_VISIBILITY unique_ptr(unique_ptr&& __u) _NOEXCEPT  

2 个答案:

答案 0 :(得分:1)

std::priority_queue::top()只有const重载返回const引用。这不能移动。

另一方面,

std::deque::front()具有const和非const重载,返回相同的限定引用。您似乎正在使用非const重载,其结果可以从。

移动

答案 1 :(得分:1)

根据documentation of std::priority_queue::top()

  

const_reference top()const;

它返回const引用,std::move将转换为const T &&。另一方const T &&移动ctor不接受std::unqiue_ptr,因为它没有这样的重载,它只接受T &&(没有const)看documentation of std::unqiue_ptr ctors }

关于std::move接受const引用的原因,请参阅此处Why can we use std::move on a const object?

相关问题