I'd like to expound upon the main answer here.
::ConstPtr
can be understood and read as "shared pointer to a constant message", and ::Ptr
can be understood and read as "shared pointer to a (modifiable) message". It's just a smart-pointer-based light-weight way of passing messages. Choose the correct one based on whether or not the recipient of the passed message will need to modify the message. Read more about std::shared_ptr<>
here: https://en.cppreference.com/w/cpp/mem....
Therefore, ::ConstPtr&
can be understood and read as "reference to a shared pointer to a constant message", and ::Ptr&
can be understood and read as "reference to a shared pointer to a (modifiable) message".
Today I think boost::shared_ptr<>
is replaced in ROS by std::shared_ptr<>
, since this is now part of the C++ Standard Library. See here: https://github.com/ros-planning/movei....
That means this is what these definitions would be today:
::Ptr
is typedef-ed to std::shared_ptr<MSG>
, which is a shared pointer to a message, and ::ConstPtr
is typedef-ed to std::shared_ptr<MSG const>
, which is a shared pointer to a const
message.
Addressing this question in the comments under the main answer:
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?
The &
is to pass the shared_ptr
object itself by reference. The shared_ptr
object is a class which manages the object it wraps and "points to", and the &
is to pass the shared_ptr
object by reference. So, we are passing a message by a reference to a smart pointer which points to it--yeah, it's kind of a double-layered approach. In C you'd just pass the message by pointer and be done, but the added benefit of using a shared pointer, which is a type of "smart pointer", is that it automatically manages the storage duration of the memory (for the message) it points to, meaning you never have to manually free or delete this dynamically-allocated memory block for the message because it's done automatically when all shared pointers to that memory are gone or out of scope.
So, passing a smart pointer saves potentially a TON of data and time in the passing of the message, and passing the smart pointer itself by reference rather than value saves a tiny bit more of data and time by not having to pass the entire smart pointer object, but rather just a reference to it. It is another small bit of savings in the message passing.
Also, I hate the names ::ConstPtr
and ::Ptr
. They create confusion. I think they should be named ::PtrToConstMsg
and ::PtrToMsg
, respectively. This is so much more clear and easy to understand. I recommend that ROS make that change.