- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
AFAIK,在下面的代码中,引用 ro1
的生命周期被延长到作用域的末尾(函数 g()
):
class Some {
// Implementation here
};
Some f() {
return Some(/* constructor parameters here*/);
}
void g() {
Some&& ro1 = f();
// ro1 lives till the end of this function
}
返回这个引用怎么样?该对象是否仍存在于 g1()
中,还是会在退出 h()
时被销毁?
Some&& h() {
Some&& ro1 = f();
// Code skipped here
return std::forward<Some>(ro1);
}
void g1() {
Some&& ro2 = h();
// Is ro2 still refering to a valid object?
}
最佳答案
How about returning this reference? Will the object still live in
g1()
没有。生命周期延长只发生一次。从 f()
返回的临时对象绑定(bind)到引用 ro1
并且它的生命周期延长到该引用的生命周期。 ro1
的生命周期在 h()
结束时结束,因此在 g1()
中使用 ro2
是悬空引用。
为了让它工作,你需要处理值:
Some h() {
Some ro1 = f();
// Code skipped here
return ro1;
}
请注意,RVO 在这里仍然适用。
关于c++ - 返回引用也会延长它的生命周期吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45653972/
我正在开发一个使用多个 turtle 的滚动游戏。玩家 turtle 根据按键命令在 Y 轴上移动。当危害和好处在 X 轴上移动时,然后循环并改变 Y 轴位置。我尝试定义一个名为 colliding(
我不明白为什么他们不接受这个作为解决方案,他们说这是一个错误的答案:- #include int main(void) { int val=0; printf("Input:- \n
我正在使用基于表单的身份验证。 我有一个注销链接,如下所示: 以及对应的注销方法: public String logout() { FacesContext.getCurren
在 IIS7 应用程序池中有一个设置 Idle-time out 默认是 20 分钟,其中说: Amount of time(in minutes) a worker process will rem
我是一名优秀的程序员,十分优秀!