且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是什么导致了这段代码中的分段错误?

更新时间:2022-06-15 08:55:18

您正在保存一个局部变量的地址,该地址已在您的列表中销毁.

You are saving an address of local variable which is destroyed in your list.

for (i = 0; i < ROBOTCOUNT; i++)
{
    ROS_INFO("Test 1");
    Robot r; <== local variable
    robotList.push_back(&r); <== save address of local
    ROS_INFO("Test 2");
}  <== r is destroyed

所以很可能你稍后会访问被删除的内存

So it's likely that you are accessing the deleted memory later

使用std::vector<:shared_ptr>>:

std::vector<std::shared_ptr<Robot>> v;
std::shared_ptr<Robot> ptr( new Robot() );
v.push_back(ptr)