c++ - Why does returning a reference to a automatic variable work? -
i'm reading c++, , read when using return reference should make sure i'm not returning reference variable go out of scope when function returns.
so why in add
function object cen
returned reference , code works correctly?!
here 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 using codeblocks ide on win7.
this undefined behavior, may seem work can break @ anytime , can not rely on results of program.
when function exits, memory used hold automatic variables released , not valid refer 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 these entities lasts until block in created exits.
Comments
Post a Comment