I'm currently reading about C++, and I read that when using return by reference I should make sure that I'm not returning a reference to a variable that will go out of scope when the function returns.
So why in the Add
function the object cen
is returned by reference and the code works 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 over Win7.
This is undefined behavior, it may seem to work properly but it can break at anytime and you can not rely on the results of this program.
When the function exits, the memory used to hold the automatic variables will be released and it will not be valid to refer to that memory.
The draft C++ standard in section 3.7.3
paragraph 1 says:
Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.
What might be happening (again, with UB, anything goes) is that since after you called Add
, you didn't call anything else, nothing has yet overridden the piece of memory where cen
was, and so the old value is still there. That being said, you cannot rely on that always happening.
You should do a memcpy to copy the object being returned to heap. Though the code works, the behaviour is undefined when returning objects that go out of scope. It may always work when the code is small, because when the function returns, the portion of the stack occupied by the function will not be cleared and since the local variables within a function will have been allocated space there, the values you get (usually) contain the values you expect. But when you have multiple functions calling each other and programs grows large, your program will start producing undefined behaviour. Possibly even seg faulting at times.