static_cast<T&&> 和 static_cast<const T&>

Kap*_*ppy 1 c++ casting reference

我想问一下有关将类型转换为T&&and 的问题const T&

int&& ref = static_cast<int&&>(1); // will ref assign to free memory? or
const int& ref = static_cast<const int&>(1);
Run Code Online (Sandbox Code Playgroud)
int&& func() {
    return 1;
}
// or
int&& func() { // call of this function always return free memory? 
    return static_cast<int&&>(1);
}
Run Code Online (Sandbox Code Playgroud)
// does static_cast<> have some different forms from casting int() (int) ?
static_cast<int&&>(1),
static_cast<const int&>(1),
or func(); // do I understand right, reference destroys with object after ';' or it returns free memory?
Run Code Online (Sandbox Code Playgroud)

Hol*_*Cat 5

两个版本都func()返回悬空引用。(这就是您所说的“空闲内存”。)

这两个ref变量不是悬空的。

您可能认为这int &&x = 1;会悬空,但引用会延长它们所绑定的临时对象的生命周期。通常,只有当引用直接绑定到临时对象时,这才有效,但有一条规则,通过强制转换进行绑定也可以做到这一点。

临时寿命延长机制鲜为人知,因此我会在现实世界中避免使用它。特别是当您的引用没有直接绑定到临时变量时,因为并非所有编译器都正确实现了这一点(GCC 失败了 1/11 测试,MSVC 失败了 6/11 测试,Clang 没问题)。