Ask Your Question
7

What is ConstPtr&?

asked 2015-07-03 14:02:45 -0500

OmoNaija gravatar image

updated 2015-07-03 14:36:57 -0500

Hey All, I'm still new to ROS and C++. I'm having trouble understanding what the ConstPtr& does when writing the callback function for a simple subscriber:

 void chatterCallback(const std_msgs::String::ConstPtr& msg) 

     {ROS_INFO("I heard: [%s]", msg->data.c_str());}

Wouldn't the code work with just:

 void chatterCallback(const std_msgs::String msg)

      {ROS_INFO("I heard: [%s]", msg);}
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
14

answered 2015-07-04 01:05:17 -0500

fergs gravatar image

updated 2018-11-10 13:11:15 -0500

ahendrix gravatar image

When messages are automatically generated into C++ code, there are several typedefs defined. One of them is ::Ptr, which is typedef-ed to be a boost::shared_ptr<MSG>, and another is ::ConstPtr which is boost::shared_ptr<MSG const>.

By passing a const pointer into the callback, we avoid doing a copy. While this might not make much difference for std_msgs::String, it can make a huge difference for sensor_msgs::PointCloud2.

edit flag offensive delete link more

Comments

Thank You!

OmoNaija gravatar imageOmoNaija ( 2015-07-06 14:28:54 -0500 )edit

thanks a lot for your help

feixiao gravatar imagefeixiao ( 2016-01-21 21:57:54 -0500 )edit

but what does & means? If msg is already a pointer, why do we take the address of msg? Or does that & means passing by reference?

wy3 gravatar imagewy3 ( 2017-07-29 15:27:13 -0500 )edit
1

@wy3: the ampersand (&) means pass by reference as you said.

ksirks gravatar imageksirks ( 2017-09-15 10:47:56 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 2015-07-03 14:02:45 -0500

Seen: 12,095 times

Last updated: Nov 10 '18