求助:这段C++程序为何崩溃或挂起直至内存耗尽?
问题分析与修复
你的程序出现挂起/内存耗尽的核心原因是无限递归构造对象:
在私有嵌套类Callback的operator()中,你创建了新的Boxbot实例Boxbot b;,而Boxbot的构造函数会循环调用callbacks(i),这又会触发新的Boxbot构造,形成无限循环,最终耗尽栈内存导致程序冻结。
你原本的意图是操作当前Boxbot对象的成员,而非新建实例,只需调整Callback的逻辑,让它直接访问原对象即可:
修复后的代码
#include <iostream> #include <functional> #include <cmath> using namespace std::placeholders; struct Goal {float x; float y;}; class Boxbot { public: Boxbot(Goal cgoals[]=0) { for (int i=0;i<3;i++) { cgoals_[i]=cgoals[i]; } for (int i=0;i<3;i++) { callbacks(*this, i); } } private: bool check_goal(Goal gl) { return std::sqrt(std::pow(gl.x,2)+std::pow(gl.y,2)) < 2; } struct Callback { void operator() (Boxbot& bot, int i) const { bot.bgoals[i] = bot.check_goal(bot.cgoals_[i]); std::printf("%s is %i\n", bot.topicns[i].data(), bot.bgoals[i]); } } callbacks; bool bgoals[3]={false,false,false}; Goal cgoals_[3]; std::string topicns[3]={"robot_1","robot_2","robot_3"}; }; int main() { Goal cgoals[3] = {{0.3,0.6},{0.9,1.2},{1.5,1.8}}; Boxbot boxbot(cgoals); return 0; }
关键修改点
- 给
Callback::operator()增加Boxbot& bot参数,传递当前要操作的对象实例,避免新建对象触发无限递归。 - 构造函数中调用
callbacks(*this, i),将当前对象的引用传入functor。 - 移除functor内的
Boxbot b;,直接通过传入的bot访问成员变量和check_goal方法。 - 补充
<cmath>头文件,确保sqrt和pow的标准定义(原代码依赖编译器扩展,标准C++需显式包含)。
运行修复后的代码,即可得到预期输出:
robot_1 is 1 robot_2 is 1 robot_3 is 0
内容的提问来源于stack exchange,提问作者rei.wmt
相关产品推荐
相关产品推荐

