Search ProofOfProgress Blog

Sunday, February 14, 2016

object lifetime of structs c++

I know when you want to return a class instance from a function you need to use the new keyword and assign it to a pointer. Is it the same rule for structs? I want my structs on the stack, not the heap. So I'd like to not mess with pointers. But I am afraid doing:
myStruct getStruct(){
  myStruct val;
  return val;
Will the instance of myStruct be killed immediately after leaving the function scope? Turns out, this works with structs. Pretty sure it would not work if it were a class. Also strange is that it seems like... All the members of a struct are initialized? Rather than having whatever random data was there before hand? Or maybe I am just lucky... Might want to explicitly init values by specifying a constructor.

No comments:

Post a Comment