Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Additional arguments for custom deleter of shared_ptr

Is there anyway I can send arguments to the deleter of std::shared_ptr?

something that would feel like:

std::shared_ptr<A> myA( a, myDeleter(a, 5) );   

where myDeleter has this signature:

void myDeleter(A* a, int i)

(Obviously the syntax above is wrong, but just to emphasize that I need my deleter to take extra arguments.)

like image 415
alexandreC Avatar asked Feb 28 '13 14:02

alexandreC


People also ask

In what situation is a shared_ptr more appropriate than a unique_ptr?

Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.

Why would you choose shared_ptr instead of unique_ptr?

Use unique_ptr when if you want to have single ownership(Exclusive) of resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. Use shared_ptr if you want to share ownership of resource .

Can you delete a shared_ptr?

[Edit: you can delete a shared_ptr if and only if it was created with new , same as any other type.

What happens when shared_ptr goes out of scope?

The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.


1 Answers

You could std::bind your deleter's second argument before passing it as the deleter:

auto deleter = std::bind(myDeleter, std::placeholders::_1, 5);
std::shared_ptr<A> myA(a, deleter);

Alternatively, your deleter could be a functor that takes the int through its constructor:

struct myDeleter
{
  myDeleter(int);
  void operator()(A*);
};

myDeleter deleter(5);
std::shared_ptr<A> myA(a, deleter);

Alternatively you could use a lambda expression:

std::shared_ptr<A> myA(a, [](A* a){ myDeleter(a, 5); });
like image 64
Joseph Mansfield Avatar answered Sep 19 '22 15:09

Joseph Mansfield