c++ - Why can I return reference to local struct variable in VS2015? -
this question has answer here:
my code follows:
#include "stdio.h" #include "string.h" struct abc { char name[20]; int n; }; struct abc& myfun(void) { struct abc x ={ "lining",99 }; return x; } int main(void) { struct abc y = myfun(); printf("%s %d\n", y.name, y.n); return 0; }
here called myfun()
, returns reference local struct abc
variable. should wrong because after myfun()
returns, memory used no longer serve. code runs in vs2015 , print correct information "lining 99".
why can outcome?
the destructor pod type struct abc
no-op.
it's wrong you're doing, happens work because destruction doesn't anything; data lost when it's overridden due stack growing on it, memory same data still there until then. don't rely on (you know it's wrong), it's doing expect, copying (now relinquished) stack frame of called function before gets overwritten subsequent calls.
Comments
Post a Comment