Arnav Borborah Arnav Borborah - 1 year ago 88
C++ Question

Should I delete pointer passed to a function as argument?

So I was reading some Stack Overflow answers about deleting pointer arguments particularly these ones(1,2), because I am building a function, that requires a pointer as an argument.

A simplified version of the function is below:

void draw(Shape * b)
//Draws code....

No what I am confused about here is deletion. For example, if the function is called like this:

Shape * c;

Then I don't have to delete anything. But if it is like this:

draw(new Shape{});

Then I do. So my question is, how should I go about deleting if the
keyword is used in the parameter. There are no possible exceptions that could be thrown in the functions, so no need for RAII. Any ideas? Please don't suggest anything involving smart pointers, because that is what I already will do, this question is curiosity. Also, please answer knowing that the function can take both the new operator, or an existing pointer, basically meaning I need a way to differentiate between both. Also, for my links: These don't really answer my question, because most of them just depend on smart pointers, or one call or the other.

Answer Source

You might use

void draw(std::observer_ptr<Shape> shape)


void draw(Shape& shape)


void draw(Shape * shape)

To be explicit that draw doesn't reclaim ownership.

and use smart pointer in signature when you reclaim it.

void Take(std::unique_ptr<Shape> shape);


void Take(std::shared_ptr<Shape> shape);