指针问题(仅在发布版本中)
不确定如何描述这一点,但我在这里:
出于某种原因,当尝试创建我的游戏的发布版本进行测试时,它的敌人创建方面不起作用。
Enemies *e_level1[3];
e_level1[0] = &Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);
e_level1[1] = &Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1);
e_level1[2] = &Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1);
这就是我创造敌人的方式。在调试配置中工作正常,但当我切换到发布配置时,它似乎无法正确初始化敌人。
对我来说,这似乎有点奇怪,它在调试中工作,但在发布中不起作用,任何帮助都可以帮助我了解主要是我做错了什么。
unsure how to go about describing this but here i go:
For some reason, when trying to create a release build version of my game to test, the enemy creation aspect of it isn't working.
Enemies *e_level1[3];
e_level1[0] = &Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);
e_level1[1] = &Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1);
e_level1[2] = &Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1);
Thats how i'm creating my enemies. Works fine when in the debug configuration but when i switch to the release config, it doesn't seem to initialize the enemies correctly.
To me, this seems a bit strange that it works in debug but not in release, any help appreciated on what mostly is what i've done wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(5)
其他人已经指出了错误,即临时对象立即被销毁,但到目前为止所有答案都使用手动内存管理 - 在 C++ 中使用例如 std::vector
对于这样的事情,例如
std::vector<Enemies> enemies;
enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1));
enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1));
enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1));
然后您只需通过 enemies[2]
作为 enemies[0]
访问 Enemies
实例,它们就会被清理掉当矢量超出时自动 范围。
该代码将指针初始化为指向立即销毁的临时对象。通过指针或引用访问不再存在的临时对象是未定义的行为。你想要:
Enemies *e_level1[3];
e_level1[0] = new Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);
e_level1[1] = new Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1);
e_level1[2] = new Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1);
您似乎正在堆栈上创建 Enemies 对象,这意味着当它们超出范围时,您的 e_level1 指针将指向已被销毁的对象。 (证明:在 Enenmies 类析构函数中放置一个断点,然后查看断点何时被击中)因此,当您尝试取消引用它们时,您将得到垃圾。
您想要的是:
for( size_t i = 0; i < 3; i++ )
e_level1[i] = new Enemies( sdlLib, ... );
这将在堆上创建对象。这也意味着您需要使用以下方法销毁对象:
for( size_t i = 0; i < 3; i++ )
delete ( e_level + i );
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
并没有按照你的想法去做。如果是构造函数调用,它会创建一个临时变量,其地址存储在 e_level1[0] 中。当 e_level1[1] 初始化时,e_level1[0] 析构函数可能已经被调用。
你可能想做
doesn't do what you think it does. If it is the constructor call, it creates a temporary and its address is stored in e_level1[0]. When e_level1[1] is initialized e_level1[0] destructor is probably already called.
You probably want to do