+ 4

Are the objects destroyed because the program ends?

https://code.sololearn.com/cvgs3XUeA8hR/?ref=app I'm pretty sure they're destroyed because the program ends, but I like to be sure. Asking because I also thought that maybe they were destroyed because the function ended.

13th Nov 2018, 10:49 PM
Daniel Cooper
Daniel Cooper - avatar
5 Respuestas
+ 6
They're local variables in main(), so they're destroyed after main() finished
14th Nov 2018, 4:17 AM
Flandre Scarlet
Flandre Scarlet - avatar
+ 5
So the stack is like a stack of boxes. Every time you call a function, a new box ("stack frame") is put atop the stack. Every variable you declare lives somewhere in the box and when the function is done, the contents are deleted (the stack frame is "teared down"). However when you allocate space on the heap, it's not affected by what is going on on the stack. Objects on the heap live until you manually free them (smart pointers aside). So you can do things like Foo* make_foo(){ Foo* f = new Foo; f->x = "I'm foo"; return f; } and it will not auto-delete once the function is done. (Note: To be correct: The *pointer* itself is still created on the stack so that will be teared down, but the content it is pointing to will not. So when you return the pointer, a copy of the pointer is created. It's a minor thing though.) (Note: Stack frames are the reason you can't do things like `char array[x]` where x is variable. Stack frame sizes are known at compile time!)
14th Nov 2018, 7:26 AM
Schindlabua
Schindlabua - avatar
+ 2
Yep they get destroyed because the function is done, and not really because the program ends. If you want objects that "live on" even after the function they were declared in ended, you'd usually use the `new` keyword. Be aware though that if your program exits, those destructors will not be called automatically, and that can get you into trouble! (Though all the space will be freed as Jay said)
14th Nov 2018, 2:43 AM
Schindlabua
Schindlabua - avatar
+ 2
Ok. Thanks everyone! Was confused. And how would I use the new keyword Schindlabua?
14th Nov 2018, 6:13 AM
Daniel Cooper
Daniel Cooper - avatar
+ 2
So how would I use this to make objects that work outside of the function they were created in?
14th Nov 2018, 6:21 AM
Daniel Cooper
Daniel Cooper - avatar