我听说c ++中的引用只能被初始化一次,但是这给了我1是我的输出而没有返回任何错误!
struct f {
f(int& g) : h(g) {
h = 1;
}
~f() {
h = 2;
}
int& h;
};
int i() {
int j = 3;
f k(j);
return j;
}
Run Code Online (Sandbox Code Playgroud)
在捕获返回值j之后调用f的析构函数.
如果你希望j为2,你可能想要这样的东西:
int i( )
{
int j=3;
{
f k(j);
}
return j;
}
Run Code Online (Sandbox Code Playgroud)
有关销毁顺序和return语句的更详细说明,请参阅C++析构函数和函数调用顺序.