开发者

Extending object lifetime

Will fnc like this extend returned object lifetime? If not, are there a ways to do so?

 const int& f () //<<----Here you see, I'm returning by ref to const int
 {
开发者_如何学编程     return 1;
 }


No, it won't extend the object lifetime.

You can't extend the lifetime of the temporary (a temporary is created for binding to the reference), but, you can simply do

int f() { return 1; }

:-)

Cheers & hth.,

– Alf


I don't think this will compile (with a constant) but if you get something similar compiled it will fail runtime with undefined behaviour.

It will not extend any lifetime so you are returning a ref to a var/const that no longer exists.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜