Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is shared_ptr<void> not specialized?

Tags:

c++

pointers

shared_ptr<void> is special in that it, by definiton, will invoke undefined behavior by calling delete on a void*.

So, why is there not a shared_ptr<void> specialization which throws a compile error?

like image 825
tenfour Avatar asked Oct 24 '11 19:10

tenfour


People also ask

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.

What happens when 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).

Are shared_ptr slow?

shared_ptr are noticeably slower than raw pointers. That's why they should only be used if you actually need shared ownership semantics. Otherwise, there are several other smart pointer types available. scoped_ptr and auto_ptr (C++03) or unique_ptr (C++0x) both have their uses.

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.


1 Answers

Using shared_ptr to hold an arbitrary object

shared_ptr can act as a generic object pointer similar to void*. When a shared_ptr instance constructed as:

shared_ptr<void> pv(new X);

is destroyed, it will correctly dispose of the X object by executing ~X.

This propery can be used in much the same manner as a raw void* is used to temporarily strip type information from an object pointer. A shared_ptr can later be cast back to the correct type by using static_pointer_cast.

But how?

This constructor has been changed to a template in order to remember the actual pointer type passed. The destructor will call delete with the same pointer, complete with its original type, even when T does not have a virtual destructor, or is void

like image 114
sehe Avatar answered Sep 21 '22 21:09

sehe