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

Last node handle goes out of scope but callbacks still work. Why?

asked 2016-08-17 05:30:41 -0500

Dimitri Schachmann gravatar image

updated 2016-08-18 03:38:34 -0500

I thought I need to keep my node handle alive by storing it in my class member, but when I make it a local variable in my constructor and let it go out of scope, my callback still gets called.

Is this proper defined behavior?

#include <ros/ros.h>
#include <std_msgs/Int32.h>

class MyNode
{

public:

    MyNode()
    {
        ros::NodeHandle nh; // will go out of scope
        subscriber = nh.subscribe("topic_name", 10, &MyNode::callback, this);
    }

private:

    void callback(std_msgs::Int32ConstPtr const & msg)
    {
        ROS_ERROR_STREAM("Callback got called");
    }

    // I thought this was mandatory
    // ros::NodeHandle nh;

    ros::Subscriber subscriber;

};

int main(int argc, char ** argv)
{
    ros::init(argc, argv, "my_node");
    MyNode node;
    ros::spin();
    return 0;
}

UPDATE:

Here it says "when the last ros::NodeHandle is destroyed, it will call ros::shutdown()". Further down it is suggested, that ros::shutdown() will make ros::spin() return. So what's up with that?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2016-08-18 09:53:41 -0500

dseifert gravatar image

If you look at https://github.com/ros/ros_comm/blob/... , the Subscriber keeps a copy/reference to the node handle. So as long as it exists, there is yet another referenced handle that will prevent the node to shut down.

edit flag offensive delete link more

Question Tools

3 followers

Stats

Asked: 2016-08-17 05:30:41 -0500

Seen: 539 times

Last updated: Aug 18 '16