【发布时间】:2017-11-12 16:22:38
【问题描述】:
为什么我们不能实现getAB() && 和getAB() 这两种方法,但可以实现其中任何一种?
代码:
struct Beta {
Beta_ab ab;
Beta_ab && getAB() && { cout << "1"; return move(ab); }
};
int main() {
Beta_ab ab = Beta().getAB();
return 0;
}
代码:
struct Beta {
Beta_ab ab;
Beta_ab && getAB() { cout << "2"; return move(ab); }
};
int main() {
Beta b;
Beta_ab ab = b.getAB();
return 0;
}
代码:
struct Beta {
Beta_ab ab;
Beta_ab && getAB() && { cout << "1"; return move(ab); }
Beta_ab && getAB() { cout << "2"; return move(ab); }
};
int main() {
Beta b;
Beta_ab ab1 = b.getAB();
Beta_ab ab2 = Beta().getAB();
return 0;
}
为什么前两个示例代码有效,但最后一个示例无效?
【问题讨论】:
-
与您的问题无关,但在创建MCVE 时请确保其中没有不相关的错误。不相关的错误会分散实际问题的注意力。我当然是在谈论您在
main函数中对变量ab的重新定义。 -
如果任何重载是引用限定的,那么 all 重载必须是引用限定的 - 将第二个重载更改为
Beta_ab && getAB() & { cout << "2"; return move(ab); }。 (不作为答案发布,因为这肯定是一个骗局。) -
可以在左值或右值上调用没有 ref 限定符的重载,例如
Beta_ab && getAB()。带有右值引用限定符Beta_ab && getAB() &&的重载只能在右值上调用。因此,如果允许两者共存,则对右值的getAB()调用将是不明确。
标签: c++ c++11 c++14 move-semantics rvalue-reference