gpt4 book ai didi

c++ - 返回引用也会延长它的生命周期吗?

转载 作者:太空狗 更新时间:2023-10-29 20:34:55 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com