Last node handle goes out of scope but callbacks still work. Why?
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?