Should I remove the pointer passed to the function as an argument?

So, I read several answers on Qaru about deleting pointer arguments, especially these ( 1 , 2 ), because I'm building a function that needs a pointer as an argument.

A simplified version of the function is below:

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

No, what confuses me is removal. For example, if a function is called like this:

Shape * c;
draw(&c);

Then I do not need to delete anything. But if so:

draw(new Shape{});

. , : , new. , , RAII. ? , , , , , . , , , , , , , . , : , .

+4
6

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

void draw(Shape& shape)

void draw(Shape * shape)

, draw .

.

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

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

, .

.

, :

  • , :

    void draw(const Shape& shape);

  • , :

    void draw(Shape& shape);

  • , :

    void draw(Shape shape);

  • , :

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

  • :

    void draw(std::shared_ptr<const Shape> shape);

+5

, , , , .

, :

Shape * pShape = new Shape(...);

draw(pShape);

delete pShape;

, :

draw(new Shape(...));  // Did the shape get deleted? Who knows...

, draw() delete - , .

(, unique_ptr<>, shared_ptr<>) . , , , , , pShape draw().

+4

, .

, . . , delete , , .

+2

RAII: , , .

, . .

draw. , . .

+1

:

void draw(Shape *&p);

if prevents:

Shape shape; // not pointer
draw(&shape);

and from:

draw(new Shape());
0
source

Source: https://habr.com/ru/post/1652339/


All Articles