ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

[Nav2] Why are smart pointers used so often, even when not necessary?

asked 2022-03-12 22:35:38 -0500

chedanix gravatar image

updated 2022-03-12 22:36:41 -0500

I started reading the source code of Nav2 and I noticed that smart pointers are used very often, even if the objects don't need to be in the heap memory.

Here is an example. In costmap_2d_ros.cpp line 130, layered_costmap_ is created with the following: layered_costmap_ = std::make_unique<LayeredCostmap>(global_frame_, rolling_window_, track_unknown_space_);

I looked at the member variables. There aren't large arrays or anything that will take up a lot of stack memory.

What is the reasoning behind using a smart pointer in such case?

edit retag flag offensive close merge delete

Comments

A costmap is a huge data structure and makes sense to allocate on the heap.

stevemacenski gravatar image stevemacenski  ( 2022-03-16 14:58:40 -0500 )edit

1 Answer

Sort by » oldest newest most voted
0

answered 2022-03-13 13:08:04 -0500

ljaniec gravatar image

A bit of explanations could be found in this ROS Answers topic there: https://answers.ros.org/question/3631...

Especially this:

One thing I noticed is that shared pointers are pervasive in that if you use shared_from_thisinside the class definition (and that happens quite a bit) so the node can pass itself to members, then it would be undefined behavior until C++17 if the node wasn't created as a shared pointer; https://en.cppreference.com/w/cpp/mem...

Certainly not great to require knowing how your instance is created/stored but that's how it is.

More information could be found on this great post with explanations: https://roboticsbackend.com/write-min..., e.g.

With ROS2 you can use Cpp 14, so ditch the “new”/”delete” keywords, and use smart pointers instead.

and

Because the node is stored in a smart pointer, you don’t need to worry about de-allocating its resources.

I dig for a moment through an issue there: https://github.com/ros2/design/issues... And I learned more too about decisions about publishers and subscribers interfaces, e.g.

The idea was that we could use smart pointers to convey the semantics of a their life cycle to the user rather than having an internally reference counted object of our own. Also in ROS 2, the Publisher and Subscription objects returned to the user are held internally as a weak_ptr, therefore if the user lets the shared pointers go out of scope they effectively unadvertised or unsubscribe them.

If you can, add more resources you have found too :) I would be interested in them as well

edit flag offensive delete link more

Question Tools

3 followers

Stats

Asked: 2022-03-12 22:35:38 -0500

Seen: 258 times

Last updated: Mar 13 '22