I am a hobbyist C++ programmer and currently working on a game (using Ogre3D) and I have a question regarding the memory allocation for my main classes.
I have read a lot on memory allocation, allocating automatically on the stack and dynamically on the heap, and their differences (performance, limited stack size). Still I am not sure what to use for my main class (Application) and some other ‘factory’ classes (created by a single instance of the Application class), which will all have a single instance existing throughout the entire execution.
Below is a simplified snippet of the layout:
int main()
{
// like this (automatic)
Application app;
app.create(); // initializing
app.run(); // runs the game-loop
// or like this (dynamic)
Application* app;
app = new Application();
app->create();
app->run();
return(0); // only reached after exiting game
}
class Application
{
public:
Application(); // ctor
~Application(); // dtor
// like this, using 'new' in ctor and 'delete' in dtor (dynamic)
SceneManager* sceneManager_; // a factory for handling scene objects
DebugManager* debugManager_; // a factory for handling debugging objects
// or like this (automatic)
SceneManager sceneManager_;
DebugManager debugManager_;
};
Is it better to allocate memory on the stack or on the heap (both for the Application class and the factory classes)? And by what arguments?
Thanks in advance!
Always prefer automatic allocation over dynamic allocation. And when you need dynamic allocation, make sure its lifetime is managed by automatically allocated resource wrappers, like smart pointers.