c++ - Value of return is not same as value actually returned? -


i've got little bug blowing mind. perhaps simple, i'm totally lost.

i have basic pod struct:

    struct data{     bool isinvalid=false;     vec3 *vector; //vec3 struct x,y,z components     node*node;     bool isfresh;     unsigned int *form;     }; 

i have function:

  data getdata(){     data forreturn;     //...populates forreturn struct     cout<<forreturn.vector->x; //logs correctly value      return forreturn;    } 

the cout log correctly shows return data has been populated. when call function function, different story presents:

  data newdata=getdata(); //logs above   cout<<newdata.vector->x; //is empty!! 

what going on here?! log output shows these 2 lines side side since occurring right after other, going on? not multithreaded, variables , pointers should not changing between these 2 lines!

i can't tell sure unless see real code have, bet program has undefined behavior, because dereferencing dangling pointer. believe in getdata() function letting forreturn.vector point local object automatic storage duration, destroyed when returning getdata(), so:

data getdata(){     data forreturn;     vec3 myvector;     // ...     forreturn.vector = &myvector; //  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^     // ...     cout<<forreturn.vector->x; // logs correctly value      return forreturn; } 

in example above returning data object forreturn value, meaning implicitly declared move constructor (in c++11) or copy constructor (in c++03) invoked.

since these implicitly-generated special member functions perform memberwise move or copy of data structure's members, vector pointer copied, meaning returning object of type data vector pointer points object has gone out of scope already.

this time bomb. pointer gets dereferenced, "boom". notice, "boom" can silent explosion - undefined behavior means anything happen, including nothing.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -