返回作为参数传递给函数的右值引用

Returning an rvalue reference that is passed to a function as an argument

我想了解我是否可以安全地 return 作为参数传递给函数的右值引用,并且它不会随着堆栈展开而被销毁。

struct Struct { int m; };

Struct& f(Struct&& rvalue)
{ 
    std::cout << &rvalue << '\n';
    return rvalue;
}

void main()
{
    Struct& lvalue1 = f(Struct{ 1 });
    std::cout << &lvalue1 << '\n';
    Struct& lvalue2 = f(Struct{ 2 });
    std::cout << &lvalue2 << '\n';

    std::cin.get();
}

输出:

00A3F844
00A3F844
00A3F838
00A3F838

此代码为右值生成不同的地址。这是否意味着 Struct 对象的实际构造发生在函数调用之前,我可以安全地执行此类操作?

I can safely do this kind of things?

没有。 Struct{ 1 }Struct{ 2 } 构造 temporary objects ,在完整表达式后被销毁。这意味着引用 lvalue1lvalue2 总是悬挂的。取消引用它们会导致未定义的行为。

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created