gpt4 book ai didi

for 循环末尾的 C++ 段错误

转载 作者:行者123 更新时间:2023-11-30 04:15:03 24 4
gpt4 key购买 nike

这段代码存在段错误,我真的不明白为什么。当我使用 gdb 时,它会在函数末尾(大括号)出现段错误。所以这并没有真正给我很多关于正在发生的事情的信息。这是代码,如果需要,我会提供额外的信息。

typedef std::list<Ground> l_Ground;

void Player::y_collisions(l_Ground grounds) {
for (l_Ground::const_iterator ent = grounds.begin(); ent != grounds.end(); ent++) {
if (getGlobalBounds().intersects(ent->getGlobalBounds())) {
in_air = false;
velocity -= gravity;
}
}
}

编辑:经过仔细检查,它可能在 for 循环的末尾出现了段错误。由于 for 循环的编写方式,这仍然没有真正意义。它不应超出列表的末尾。

EDIT2:由于下面的答案,这将起作用。

typedef std::list<Ground> l_Ground;

void Player::y_collisions(const l_Ground& grounds) {
for (l_Ground::const_iterator ent = grounds.begin(); ent != grounds.end(); ent++) {
if (getGlobalBounds().intersects(ent->getGlobalBounds())) {
in_air = false;
velocity -= gravity;
}
}
}

最佳答案

您按值传递了 grounds 参数。这意味着制作了一份 list 的拷贝。 显然你的 Ground 类有一个损坏的复制构造函数,这使得 getGlobalBounds() 方法引用了一些无效的指针,从而导致了崩溃。

你几乎不应该按值传递一个大对象,除非你想立即复制它。始终训练自己始终键入 const & :).

关于for 循环末尾的 C++ 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18578631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com