TransformBroadcaster as member of ROS2 Node
What is the proper way to create a tf2_ros::TransformBroadcaster
inside a rclcpp::Node
?
I am trying to create a TransformBroadcaster
as a member of a ROS2 node, i.e. constructing from this
.
So far, I am constructing the ROS2 node member tf_broadcaster
from a shared pointer to this
:
MyNode::MyNode() : Node("my_node", "node_namespace", true) {
// in header: std::unique_ptr<tf2_ros::TransformBroadcaster> tf_broadcaster;
tf_broadcaster = std::make_unique<tf2_ros::TransformBroadcaster>(rclcpp::Node::SharedPtr(this));
}
This seems to work in general, e.g. I can publish my transforms. However, I get a double free corruption error when the node is deconstructed, because the node is deconstructed a second time when shared_ptr
goes out of scope.
Neither this->shared_from_this()
(error at construction: terminate called after throwing an instance of 'std::bad_weak_ptr') nor std::shared_ptr<rclcpp::Node>(this)
(error at deconstruction: free(): invalid pointer) allow me to create a shared pointer of this.
Wouldn't it be easier, if the rclcpp::Node
would inherit the transformer methods from a TransformBroadcaster
class instead of instantiating it manually? E.g. class MyNode : public rclcpp::Node, tf2_ros::TransformBroadcaster {}
and then just call this->sendTransform(tf);
.
I had a TransformBroadcaster member variable that couldn't be constructed from shared_from_this at container class construction time, so I made it a shared ptr and initialized that later, which appeared to function but ctrl-c wouldn't kill the node properly (two ctrl-c in a row would work)
weak_ptr would break the cyclical shared_ptr there.