提问人:yano 提问时间:9/22/2021 更新时间:9/22/2021 访问量:737
无法分配具有已删除复制构造函数的引用?
Cannot assign a reference that has a deleted copy constructor?
问:
我处于需要为一个类实现 Move 构造函数和 Move-Assignment 运算符的情况,该类包含对具有已删除的 Copy Ctor 和 Copy-Assignment 运算符的对象的引用,基本上如下所示:
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 构造函数,然后使用它来实现 Move-Assignment 运算符?
- 我没有意识到在这种情况下,编译器会在重新分配现有引用时生成副本。谁能解释呢?
答: 暂无答案
评论
mThing = other.mThing;
mThing
mThing
std::move()
MoveOnlyThing
mThing = std::move(other.mThing);