1
$\begingroup$

What is the difference between the 2 pieces of code -

tf2_ros::Buffer buffer(ros::Duration(10)); 


costmap_2d::Costmap2DROS costmap_one("costmap_one", buffer); 

and

costmap_2d::Costmap2DROS *costmap_one = new costmap_2d::Costmap2DROS("costmap_one", buffer)

I understand that in the first case, we get a costmap_2d::Costmap2DROS object named costmap_one whereas in the second case, we get a pointer named costmap_one that points to a costmap_2d::Costmap2DROS object.

When should we use one over the other?

$\endgroup$

1 Answer 1

3
$\begingroup$

IMHO the main difference is, that inside function/method the first one (object) is allocated on the stack and destroyed after leaving the function, while the other (pointer) allocates its data on the heap, so it can be safely returned from the function and survive its end. It must be destroyed more explicitly, when you want to get rid of it.

Allocating on the stack does not fragment the memory and living scope is clearly visible. Allocating on the heap may fragment the memory, may stay living much longer than needed and its living scope is much less clear - but can be used for making more complicated structures such as graphs, buffers and similar ...

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.