#include <iostream>
using namespace std;
struct CL
{
CL()
{
cout<<"CL()"<<endl;
}
CL(const CL&)
{
cout<<"CL(const CL&)"<<endl;
}
~CL()
{
cout<<"~CL()"<<endl;
}
};
CL cl;
CL fnc()
{
return cl;
}
int main() {
cout<<"start"<<endl;
const CL& ref=static_cast<const CL&>(fnc());
//...Is "ref" valid here??
cout<<"end"<<endl;
return 0;
}
fnc()返回的临时对象的生命周期是"ref"的生命周期还是static_cast(fnc())的临时引用的生命周期(在语句结束时销毁)?
gcc的输出结果(fnc()的生命周期是"ref"的生命周期):
CL() //global object "cl"
start
CL(const CL&)
end
~CL()
~CL() //global object "cl"
VS2013的输出结果(fnc()的生命周期是临时引用的生命周期):
CL() //global object "cl"
start
CL(const CL&)
~CL()
end
~CL() //global object "cl"
标准中的正确指的是什么?
static_cast<>
会发生什么?我期望两者的行为都应该相同,以防你有一个真正想要解决的问题。另外,你对标准关于这个问题的解释是什么? - Ulrich Eckhardtstatic_cast
。如果没有它,fnc()
的生命周期将会被保证延长到ref
的生命周期。 - Angew is no longer proud of SOstatic_cast
的情况下是这样的。 - Angew is no longer proud of SO