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.)
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.
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 .
[Edit: you can delete a shared_ptr if and only if it was created with new , same as any other type.
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With