最小工作示例。在C++中移出std priority_queue的元素11
#include <cassert>
#include <list>
#include <queue>
//#define USE_PQ
struct MyClass
{
const char* str;
MyClass(const char* _str) : str(_str) {}
MyClass(MyClass&& src) { str = src.str; src.str = nullptr; }
MyClass(const MyClass&) = delete;
};
struct cmp_func
{
bool operator() (const MyClass&, const MyClass&) const
{
return true;
}
};
typedef std::priority_queue<MyClass, std::vector<MyClass>, cmp_func> pq_type;
#ifdef USE_PQ
MyClass remove_front(pq_type& l)
{
MyClass moved = std::move(l.top());
// error from the above line:
// use of deleted function ‘MyClass::MyClass(const MyClass&)’
l.pop();
return std::move(moved);
}
#else
MyClass remove_front(std::list<MyClass>& l)
{
MyClass moved = std::move(l.front());
l.erase(l.begin());
return std::move(moved);
}
#endif
int main()
{
const char* hello_str = "Hello World!";
MyClass first(hello_str);
#ifdef USE_PQ
pq_type l;
l.push(std::move(first));
MyClass moved = remove_front(l);
#else
std::list<MyClass> l;
l.push_back(std::move(first));
MyClass moved = remove_front(l);
#endif
assert(moved.str);
assert(!first.str);
return 0;
}
所以这个工程。现在删除第4行的注释符号,它表示需要复制构造函数(我的被删除)。此外,它错过operator=
。问题:
- 这里有什么区别?
- 问题能解决吗?如果是的话,如果不是,为什么不呢?
注意:您也可以使用boost的priority_queue作为您的答案,但我得到了与它相同的错误。
'priority_queue :: top()'返回const引用,所以即使移动它仍然是一个左值。 –
@ C.R。 'std :: move'只是对右值引用的强制转换,因此即使无法通过它获取资源,任何类型为'const T'的左值都将被转换为const t &&,这是一个右值。 – dyp