Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a shared_ptr store deleter?

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?

like image 474
Toccio Avatar asked Sep 03 '14 23:09

Toccio


People also ask

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.

Why would you choose shared_ptr instead of unique_ptr?

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.

Can you move shared_ptr?

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).


1 Answers

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.

like image 189
Kerrek SB Avatar answered Oct 12 '22 18:10

Kerrek SB