考虑以下函数。我想要C++17的答案。
MyClass&& func() {
return MyClass{};
}
int main() {
MyClass&& myRef = func();
}
Run Code Online (Sandbox Code Playgroud)
问题:
func()x 值吗?为什么?myRef悬空引用?或者,更具体地说,为什么要func()返回悬空引用?返回右值引用不会导致临时物化并延长临时对象的生命周期吗?考虑代码:
list<int> a{ 4,3,1,2 };
auto i = a.begin();
swap(*i, *(++i));
Run Code Online (Sandbox Code Playgroud)
为什么交换什么都不做?虽然以下按预期工作?
list<int> a{ 4,3,1,2 };
auto i = a.begin();
swap(*i, *(next(i)));
Run Code Online (Sandbox Code Playgroud)