C ++: reference to an object "out of scope"

There is one thing that I never understood regarding links, and I hope someone can help me. As far as I know, the link cannot be null. But what happens if you have a foo () function that returns a reference to a stack object:

Object & foo(){ Object o; return o; } Object & ref = foo(); 

Theoretical refling will refer to a non-existent object, since o leaves the scope immediately after the function returns. What's going on here?

+6
source share
3 answers

This causes undefined behavior. Do not do this.

The implementation, realistic, the link will point to the stack, where there used to be a stack stack for calling foo . In many cases, this memory still makes sense, so the error is often not immediately obvious. Therefore, you should ensure that you never make such a link.

+10
source

nothing before using the returned link - then you will read / write through your stack

+1
source

Undefined behavior in this context is not particularly strange in C ++. This is essentially identical to the situation when you have a pointer to a local variable that is out of scope. C ++ requires you to reference processing descriptors and the lifetime of reference objects.

+1
source

Source: https://habr.com/ru/post/912038/


All Articles