In the past whenever I needed to create an instance of a class I would use new to allocate it on the heap (except for stl classes, and math classes like vec3 and mat4).
However, I was just looking critically at some of my code and realized that technically I could just be making these classes on the stack instead. They're not very big, don't need to be modified outside of their current scope, etc. When I (occasionally) need to pass them to another function I can use a reference as easily as I could pass a pointer.
In the past I always defaulted to allocating on the heap, and only used the stack in certain cases, however now I'm wondering if it would have been better to default to allocating on the stack, and only use the heap when
- a pointer is really needed (ie the lifetime of the object to outlast the scope of declaration)
- the class or array is too big for the stack
- inheritance requires it (abstract base class/interface)
- something else?
Which also raises the question: how big a class is too big (roughly) to reasonably allocate on the stack? (assuming we're working on, at minimum, smartphones, and going up to high end desktops) Am I just worrying unnecessarily about stack size constraints? (probably, as long as we're not talking large arrays, and no class is going to be even close to a kilobyte)