Contents
The ros::NodeHandle class serves two purposes. First, it provides RAII-style startup and shutdown of the internal node inside a roscpp program. Second, it provides an extra layer of namespace resolution that can make writing subcomponents easier.
Automatic Startup and Shutdown
As explained in the Initialization and Shutdown roscpp overview, ros::NodeHandle manages an internal reference count to make starting and shutting down a node as simple as:
1 ros::NodeHandle nh;
On creation, if the internal node has not been started already, ros::NodeHandle will start the node. Once all ros::NodeHandle instances have been destroyed, the node will be automatically shutdown.
Namespaces
See also: ROS names documentation
NodeHandles let you specify a namespace to their constructor:
1 ros::NodeHandle nh("my_namespace");
This makes any relative name used with that NodeHandle relative to <node_namespace>/my_namespace instead of just <node_namespace>.
You can also specify a parent NodeHandle and a namespace to append:
This puts nh2 into the <node_namespace>/ns1/ns2 namespace.
Global Names
If you really want you can specify a global name:
This is generally discouraged, as it prevents nodes from being pushed into namespaces (e.g. by roslaunch). There are times, however, when using global names in code can be useful.1 ros::NodeHandle nh("/my_global_namespace");
Private Names
Using private names is a little bit tricker than calling a NodeHandle method with a private name ("~name") directly. Instead, you must create a new NodeHandle located inside a private namespace:
The above example will subscribe to <node_name>/my_private_namespace/my_private_topic. See also roscpp_tutorials.