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

Getting a Node::SharedPtr from "this"

asked 2020-06-02 05:38:30 -0600

KenYN gravatar image

A number of functions expect a rclcpp::Node::SharedPtr, but when you are in an rclcpp::Node subclass it is not available, and of course something like foo(rclcpp::Node::SharedPtr(this)); is a great way to crash your program. Is there some registry of these SharedPtrs to query?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
7

answered 2020-06-02 11:49:45 -0600

sloretz gravatar image

rclcpp::Node inherits from std::enable_shared_from_this<>. You can get a shared pointer to a node by calling shared_from_this() in your subclass. There's more info about std::enable_shared_from_this<> here.

edit flag offensive delete link more

Comments

6

An important caveat is you can't call shared_from_this in your class's constructor because the object doesn't yet fully exist to make a shared_ptr from. There you can only use APIs that use either a raw pointer or individual node interfaces.

jdlangs gravatar image jdlangs  ( 2020-06-08 13:42:35 -0600 )edit
1

I realize this thread is old, but what is the reason you can still do this->create_publisher<std_msgs::msg::String>("topic", 10); in the constructor? Wouldn't the same reason - that the object doesn't fully exist yet - still apply?

swiz23 gravatar image swiz23  ( 2023-03-06 13:50:02 -0600 )edit
1

@swiz23 Looks like I phrased it badly. The object does exist from the time the constructor body starts since initialization is completed at that point. But shared_from_this requires a shared_ptr to already be managing the object and that won't be created until after the constructor returns (assuming you're using something like make_shared).

jdlangs gravatar image jdlangs  ( 2023-03-13 16:54:36 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2020-06-02 05:38:30 -0600

Seen: 5,025 times

Last updated: Jun 02 '20