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

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

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

Dimitri Schachmann gravatar image

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

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


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


    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;
    return 0;


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

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

dseifert gravatar image

If you look at , 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



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

Seen: 524 times

Last updated: Aug 18 '16