I have been researching into RAII (http://tomdalling.com/blog/software-design/resource-acquisition-is-initialisation-raii-explained/) and have a number of questions!
There are some strong arguments for initialising objects on the stack. Is there ever a good scenario to allocate memory on the heap?
How does this work with polymorphic objects? For example, you have an abstract base class called Biome
and you need a container of biomes. This container needs to store objects of Ocean
, Tundra
, Desert
etc. Are there any issues or strong arguments against allocating these objects on the stack, but then storing pointers to these objects in a container of pointer to Biome? I am aware that once the encapsulating objects go out of scope, these objects will be destroyed and their pointers will be addressed to memory which potentially does not exist.
There are some strong arguments for initializing objects on the stack. Is there ever a good scenario to allocate memory on the heap?
You certainly need to allocate objects in the heap when the number of objects or their actual type is known only at runtime (not at compile time) or when it is large. You don't want to have large call stack frames (a typical frame should be less than a kilobyte, since the entire stack is less than two megabytes and you could have recursive, or simply very deep, functions).
How does this work with polymorphic objects? For example, you have an abstract base class called Biome and you need a container of biomes. This container needs to store objects of Ocean, Tundra, Desert etc.
Your container will in fact store pointers to these objects. Of course, you may want to have smart pointers.