ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

shared pointer vs make shared ros2

asked 2021-07-19 10:51:45 -0500

What is the difference between make shared and shared pointer? Accompanied by relevant links/information about the two as a basis would help when explaining. When/why would one be chosen over the other?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-07-19 13:48:25 -0500

updated 2021-07-19 13:49:31 -0500

A shared pointer is the pointer to the object (e.g. shared_ptr<Object>) that your program will use. You have options between shared, unique, weak, and auto -- each have different semantics and uses in programs.

make_shared is simply the factory to create this shared pointer to your object. On construction, you could use new to allocate your memory of your new pointer object, but there are various reasons why you might not want to populate your shared pointer on construction. For instance if you have a shared pointer in your program as a class member that you want to populate only after you've configured your program since the object needs some of those parameters.

So make_shared is a convenient factory to populate your shared pointer by passing through the constructor arguments to Object and returning a shared_ptr which you're using to actually accomplish your intended task. make_shared returns a shared_ptr.

Ex.

shared_ptr<Object> obj_ptr;
... configurations ...
obj_ptr = make_shared<Object>(object_argument_1, object_argument_2, ...);
obj_ptr->getThing();
edit flag offensive delete link more

Question Tools

Stats

Asked: 2021-07-19 10:51:45 -0500

Seen: 598 times

Last updated: Jul 19 '21