I can't understand how a shared_ptr
can store the deleter that I gave to it.
Initially, using a shared_ptr<int>
, i thought it might use an std::function<void(int*)>
, but i can give, as a deleter, any kind of function (or callable objects), as long as the first parameter is a int*
.
How can shared_ptr
do this?
I'm sorry if this is a silly question, I'm new to C++, forgive me!
Edit: The question is: how can I do something like that? What should I use? Any example? Or it is a very advanced topic?
[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.
In short: 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.
By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr . "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and causing atomic reference increment or decrement).
The deleter, as well as the allocator, are type-erased. The shared pointer manages a dynamically allocated, private, templated control object, which is accessed through a polymorphic base and which stores all the type-specific state and functionality.
The implementation of std::function
uses similar ideas, since it is also a type-erasing dynamic manager class, but both are typically implemented entirely separately.
The upshot is that both classes are comparatively "expensive" and should only be used when they are genuinely necessary. Otherwise, cheaper, non-polymorphic non-dynamic solutions are usually preferable.
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