[英]Why std::queue requires the element to be copyable?
在std::deque
下面的代码中编译,但std::queue
没有:
class A
{
public:
explicit A(int a) : m_a(a)
{
++count;
}
~A()
{
--count;
}
A(A const &) = delete;
A(A && other) : A(other.m_a)
{
other.m_moved = true;
}
A & operator = (const A &) = delete;
A & operator = (A && other)
{
m_a = other.m_a;
other.m_moved = true;
return *this;
}
bool operator == (const A & other) const
{
return m_a == other.m_a;
}
bool operator != (const A & other) const
{
return !operator==(other);
}
bool operator < (const A & other) const
{
return m_a < other.m_a;
}
static int count;
private:
bool m_moved = false;
int m_a;
};
int A::count = 0;
int main()
{
std::deque<A> d;
std::queue q(d);
q.push(A(1));
return 0;
}
但是如果我通过更改A(A const &) = delete;
使 class A
复制; 使用A(A const &) = default;
它开始编译。
这背后的逻辑是什么? 据我所知, std::deque
是一个不添加一些额外功能的适配器。
当您从 deque 构造队列时会复制元素,但是您已经删除了 deque 的值类型 ( A
) 的复制构造函数。 所以在构建队列的时候需要移动d
。
...
int main()
{
std::deque<A> d;
std::queue q(std::move(d)); // added std::move
q.push(A(1));
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.