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?
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.
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).
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.
[Edit: you can delete a shared_ptr if and only if it was created with new , same as any other type.
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.
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
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