asele
asele

Reputation: 52

Why unique_ptr's Deleter need an argument of type unique_ptr<T, Deleter>::pointer?

I see the describtion about unique_ptr on cppreference, it says Deleter must be FunctionObject or lvalue reference to a FunctionObject or lvalue reference to function, callable with an argument of type unique_ptr<T, Deleter>::pointer, I don't understand why there is such a requirement that FunctionObject must have an argument and if I want to implement the requirement,How shoud I do?

Upvotes: 0

Views: 590

Answers (1)

Caleth
Caleth

Reputation: 62894

That requirement is expressing that unique_ptr more or less looks like this:

class unique_ptr {
    pointer ptr;
    [[no_unique_address]] deleter_type del;
public:
    /* other members */
    ~unique_ptr() { del(ptr); } 
};

That is, it ensures that the pointed-to value is "freed" when the pointer is destroyed, whatever "freed" means.

std::default_delete is similarly more or less:

struct default_delete {
    void operator()(pointer ptr) const { delete ptr; }
};

So if you want to write a custom deleter, it should have a member function void operator()(pointer ptr) const, in which you do whatever cleanup.

Upvotes: 1

Related Questions