Rod*_*tro 1 c++ memory-management operator-overloading
我的一堂课遇到了问题.我有这两个类,GameApp和Simulation:
GameApp.h
#pragma once
#include "Simulation.h"
class Simulation;
class GameApp {
static GameApp *instance;
public:
~GameApp(void);
static GameApp *initializeContext(const char *gameTitle, const int windowWidth, const int windowHeight);
//void setSimulation(Simulation &simulation) { *(this->simulation) = simulation; }
Simulation *getSimulation() { return simulation; }
static const int TARGET_FPS = 50; // Frames per second
private:
GameApp(void);
Simulation *simulation;
double frameIntervalList[TARGET_FPS]; // A list containing the time to render the last 60 frames
// Other stuff that doesn't matter
Run Code Online (Sandbox Code Playgroud)
Simulation.h
#pragma once
#include <vector>
#include "GameApp.h"
class Simulation {
public:
Simulation(void);
Simulation(const Simulation ©);
~Simulation(void);
Simulation &operator=(const Simulation &other);
protected:
std::vector<Entity*> *entities;
Run Code Online (Sandbox Code Playgroud)
而且,在GameApp.cpp中,在函数中initializeContext,我有:
#include "GameApp.h"
GameApp *GameApp::instance = NULL;
GameApp::GameApp() {
gamePaused = false;
frameIntervalSum = 0;
this->simulation = new Simulation();
for (int i = 0; i < 60; i++) {
frameIntervalList[i] = 0;
}
}
GameApp *GameApp::initializeContext(const char *gameTitle, const int windowWidth, const int windowHeight) {
instance = new GameApp();
// (...) Rest of initialize funcion
}
Run Code Online (Sandbox Code Playgroud)
问题是,出于一些神秘的原因,当我调用时initializeContext,它的第一行调用GameApp的构造函数,它创建一个新的Simulation,它正确分配并获得模拟指针的内存地址.但是当程序退出GameApp的构造函数时,在后面的行中instance = new GameApp();,如果我使用调试器检查simulator新创建的变量instance,我得到的指针值,我刚创建0x00000000的Simulation那个就消失了.如果我在构造函数上使用堆栈内存,确实会发生这种情况,但我正在使用new,我猜想以正确的方式创建新的Simulation变量.这里可能会发生什么?
此外,文件setSimulation上还有一个注释功能GameApp.h.当我把这个没有注释时,我得到编译器错误2582,"运算符=函数在模拟中不可用".这可能与我的问题有关吗?
编辑:问题确实是硬编码大小的for循环.我frameIntervalList在标题中将大小从60改为50但忘记在循环中更改它.还更新了代码以显示声明frameIntervalList.
在simulation成员变量的初始化和GameAppctor 之后的代码之间执行的唯一代码是初始化的for循环,frameIntervalList因此simulation如果你不幸,它的硬编码大小的初始化可能会覆盖变量的值.(或者幸运,因为它可以帮助你早点抓到一个非常丑陋的虫子!!! :-)