CMake File Example From Official Guide

[ROS/C++] Using smart pointers in containers

Author posted @ 2014年8月17日 17:35 in C/C++ with tags c++ ROS , 2721 阅读

Problem Description:

The memory leak problem was found when I tested the ROS simulation of a large number of robots, say, 50. Basically I have one simulator node and 50 robot controller nodes. Occasionally after running the program for a while, the simulator node may throw a bad_alloc exception and then terminated.

Solution:

As these two figures shown, in the launch file, I set the 'launch-prefix="gdb  -ex run --args" ' attribute in each <node> tag [1]. (Acturally setting this attribute to simulator node only is enough.)

By observing the information from GDB, I got that in the simulator class I defined, I had a map container, where the robot id (integer) is the key, and the pointer to each simulatedrobot object is the value, like:

class Simulator{
private:
   int num_robots;
   map<int, SimulatedRobot*> allrobots;
   ...
}; 

And in the constructor of the Simulator class, I have following codes like:

Simulator::Simulator(){
   for(int i=0; i< num_robots; i++){
      SimulatedRobot* sr = new SimulatedRobot(i);
      allrobots.insert(map<int, SimulatedRobot*>::value_type(i, sr);
   }
   ... 
}

I realized I did not deallocate the memory properly so the memory leaking exists.

By reading C++ Coding Standard Rule 79: "Store only values and smart pointers in containers" [4]. I changed my implementation using std::shared_ptr [2],[3]. Therefore, the code looks like:

class Simulator{
private:
   int num_robots;
   map<int, std::shared_ptr<SimulatedRobot> > allrobots;
   ...
}; 
...

Simulator::Simulator(){
   for(int i=0; i< num_robots; i++){
      std::shared_ptr<SimulatedRobot> sr = std::make_shared<SimulatedRobot>(i);
      allrobots.insert(map<int, std::shared_ptr<SimulatedRobot> >::value_type(i, sr);
   }
   ... 
}

References:

[1]. Roslaunch Nodes in Valgrind or GDB

[2]. Smart Pointers

[3]. Shared_ptr

[4]. C++ Coding Standard

Vivo V7+ Review 说:
2018年5月24日 04:55

By reading C++ Coding Standard Rule 79: "Store only values and smart pointers in containers" [4]. I changed my implementation using std

Lachlan Townley 说:
2018年7月14日 22:29

This is quite helpful option for users of the containers that help them into using of different types of pointers in right way. Writing of essay paper is become easy for us because uk essay writing services with students get best results.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter