Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ When to allocate on heap vs stack?

Whilst asking another question (and also before) I was wondering how do I judge whether to create an object on the heap or keep it as an object on the stack? What should I ask myself about the object to make the correct allocation?

like image 259
user997112 Avatar asked Oct 19 '25 03:10

user997112


2 Answers

Put it on the heap if you have to, the stack if you can.

What kinds of things do you need to put on the heap? Anything of varying length. Any object that might need to be null. Anything that's very large, lest you cause a stack overflow.

like image 93
Steve Howard Avatar answered Oct 21 '25 18:10

Steve Howard


Simple answer.

When it goes out of scope, do you want it to hang around and be able to use it?

like image 38
Ed Heal Avatar answered Oct 21 '25 16:10

Ed Heal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!