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

Popular posts from this blog

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

Making Empty C++ Project: General exception (Exception from HRESULT:0x80131500) Visual Studio Community 2015 -

How to fix java warning for "The value of the local variable is not used " -