【发布时间】:2011-07-01 16:22:10
【问题描述】:
我是一名 C++ 程序员爱好者,目前正在开发一款游戏(使用 Ogre3D),我对我的主类的内存分配有疑问。
我已经阅读了很多关于内存分配、在堆栈上自动分配和在堆上动态分配的内容,以及它们的区别(性能、有限的堆栈大小)。我仍然不确定我的主类(Application)和其他一些“工厂”类(由 Application 类的单个实例创建)使用什么,它们在整个执行过程中都存在一个实例。
下面是布局的简化sn-p:
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_;
};
在堆栈上还是在堆上分配内存更好(应用程序类和工厂类)?以及依据什么论据?
提前致谢!
【问题讨论】:
标签: c++ performance heap-memory stack-memory