roscpp overview: Initialization and Shutdown | Basics | Advanced: Traits [ROS C Turtle] | Advanced: Custom Allocators [ROS C Turtle] | Advanced: Serialization and Adapting Types [ROS C Turtle] | Publishers and Subscribers | Services | Parameter Server | Timers (Periodic Callbacks) | NodeHandles | Callbacks and Spinning | Logging | Names and Node Information | Time | Exceptions | Compilation Options | Advanced: Internals | tf/Overview | tf/Tutorials | C++ Style Guide

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.


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:

   1 ros::NodeHandle nh1("ns1");
   2 ros::NodeHandle nh2(nh1, "ns2");

This puts nh2 into the <node_namespace>/ns1/ns2 namespace.

Global Names

  • If you really want you can specify a global name:

       1 ros::NodeHandle nh("/my_global_namespace");
    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.

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:

       1 ros::NodeHandle nh("~my_private_namespace");
       2 ros::Subscriber sub = nh.subscribe("my_private_topic", ...);

    The above example will subscribe to <node_name>/my_private_namespace/my_private_topic. See also roscpp_tutorials.

Wiki: roscpp/Overview/NodeHandles (last edited 2021-06-10 10:32:11 by IsaacSaito)