我的情况是,我需要为一个类实现移动构造函数和移动分配运算符,该类包含对具有已删除复制函数和复制分配运算符的对象的引用,基本上如下所示:
class MoveOnlyThing
{
public:
MoveOnlyThing() = default;
MoveOnlyThing(const MoveOnlyThing&) = delete;
MoveOnlyThing& operator=(const MoveOnlyThing&) = delete;
};
class Holder
{
public:
Holder(MoveOnlyThing& t)
: mThing(t)
{
}
Holder(Holder&& other)
: mThing(other.mThing)
{
}
Holder& operator=(Holder&& other)
{
mThing = other.mThing;
return *this;
}
MoveOnlyThing& mThing;
};
现在,问题是, 的分配mThing = other.mThing;
正在发出错误:
main.cpp:40:16: error: overload resolution selected deleted operator '='
mThing = other.mThing;
~~~~~~ ^ ~~~~~~~~~~~~
main.cpp:20:12: note: candidate function has been explicitly deleted
MoveOnlyThing& operator=(const MoveOnlyThing&) = delete;
^
提出了两个问题;
- 我们如何处理这个问题?实现Move Constructor,然后用它来实现Move-Assignment Operator?
- 我没有意识到在重新分配现有引用时编译器会在这种情况下生成一个副本。谁能解释一下?