对于以下代码,我理解为什么在第一个示例中,临时对象的生存期得到延长,但为什么在第二个示例中没有发生该生存期延长的原因:
#include <iostream>
struct A
{
A() { std::cout << "construct A:" << this << "\n"; }
~A() { std::cout << "destruct A:" << this << "\n"; }
A & operator () (int i) & { std::cout << "int&" << this << "\n"; return *this; }
A && operator () (int i) && { std::cout << "int&&:" << this << "\n"; return std::move(*this); }
};
int main()
{
{
std::cout << "\nNOT DANGLING...\n";
A && a = A()/*(32)(42)*/;
std::cout << "using...\n";
a(52)(62); // OK: No dangling reference
} // NORMAL: Temporary destroyed at end of scope
{
std::cout << "\nDANGLING...\n";
A && a = A()(32)(42); // PROBLEM: Temporary immediately destroyed
std::cout << "using...\n";
a(52)(62); // ERROR: Dangling reference
}
return 0;
}
Compiler Explorer的输出为:
NOT DANGLING...
construct A:0x7ffc7b1f08fe
using...
int&0x7ffc7b1f08fe
int&0x7ffc7b1f08fe
destruct A:0x7ffc7b1f08fe
DANGLING...
construct A:0x7ffc7b1f08ff
int&&0x7ffc7b1f08ff
int&&0x7ffc7b1f08ff
destruct A:0x7ffc7b1f08ff
using...
int&0x7ffc7b1f08ff
int&0x7ffc7b1f08ff
为什么在第二个示例中,临时临时对象被立即销毁了,而我却留下了一个悬空的指针?
(注意:这发生在使用C ++ 11或C ++ 17的GCC和Visual Studio上)