假设我有一个只能移动的类,并且这个类有“链接”的方法。示例:
struct C {
C() = default;
C(C const&) = delete;
C(C&&) = default;
C& chained() {
return *this;
}
int a;
};
C foo(C c) {
return c.chained();
}
int main()
{
auto o = foo(C{});
}
我在 foo 的返回语句中收到错误消息:“使用已删除的函数‘C::C(const C&)’”。
为什么要尝试调用复制构造函数?它不应该使用 move 构造函数,因为它是 return 语句吗?
最佳答案
Why is trying to call the copy constructor? Shouldn't it be using the move constructor since its a return statement?
没有。您指的是并误解了 copy elision (关于 NRVO)。只有当返回的表达式是一个 id-expression(只是一个名称),它引用函数参数列表中的对象或本地对象时,才会首先尝试移动。
您不返回 id 表达式,您的表达式是调用成员函数的结果。
关于c++ - 返回 "chained"对象时移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52872578/