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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With