Why is the reference to an automatic variable returned?

I am currently reading about C ++, and I read that when using return by reference I have to make sure that I am not returning a reference to a variable that will go out of scope when the function returns.

So why in the Add function the cen object is returned by reference and the code is working correctly ?!

Here is the code:

 #include <iostream> using namespace std; class Cents { private: int m_nCents; public: Cents(int nCents) { m_nCents = nCents; } int GetCents() { return m_nCents; } }; Cents& Add(Cents &c1, Cents &c2) { Cents cen(c1.GetCents() + c2.GetCents()); return cen; } int main() { Cents cCents1(3); Cents cCents2(9); cout << "I have " << Add(cCents1, cCents2).GetCents() << " cents." << std::endl; return 0; } 

I am using CodeBlocks IDE on top of Win7.

+6
source share
3 answers

This is an undefined behavior , it may seem that it works correctly, but it can break at any time, and you cannot rely on the results of this program.

When the function exits, the memory used to store the automatic variables will be released, and it will not be valid for accessing this memory.

The draft C ++ standard in section 3.7.3 in paragraph 1 says:

Variable scopes explicitly declared by the register or not explicitly declared static or external have automatic storage duration. Storage for these objects continues until the creation of the block in which they are created is completed.

+7
source

What can happen (again, with UB, everything goes) is that after you called Add , you did not write anything, you did not redefine the piece of memory where cen was, and so the old value still exists . However, you cannot rely on what always happens.

+1
source

You must do memcpy to copy the returned object to the heap. Although the code works, the behavior is undefined when returning objects that are out of scope. It can always work when the code is small, because when the function returns, the part of the stack occupied by this function will not be cleared, and since the local variables inside the function will be allocated space there, the values ​​you get (usually) contain the values ​​that you expect. But when you have several functions that call each other, and the programs become large, your program will begin to create undefined behavior. Perhaps even sometimes a crash occurs.

+1
source

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


All Articles