Reading Alexandrescu and wikipipidia I see the pointee and the reference counter are stored on the heap. Then there is mention that reference counting is inefficient as counter must be allocated on the heap? Why isn't it stored on the stack?
As shown in the example, a smart pointer is a class template that you declare on the stack, and initialize by using a raw pointer that points to a heap-allocated object.
If you find that you need to share data or utilize reference counting, you should use a std::shared_ptr . If you need to reference shared data but don't want to contribute to the reference count, use a std::weak_ptr .
The shared reference counter counts the number of owners. Copying a std::shared_ptr increases the reference count by one. Destroying a std::shared_ptr decreases the reference count by one. If the reference count becomes zero, the resource will automatically be released.
A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it. The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by boost::scoped_ptr or std::unique_ptr .
Because you would lose it as soon as the current instance of the smart pointer goes out of scope.
A smart pointer is used to simulate automatic storage objects that were allocated dynamically. The smart pointers themselves are managed automatically. So when one is destroyed, anything it stores in automatic storage is also destroyed. But you don't want to lose the reference counter. So you store it in dynamic storage.
It can't be stored on the stack because then a copy of the object would also result in a copy of the refcount, which would defeat its purpose.
As others have pointed out, the stack isn't an appropriate place to keep the reference count because the object may outlive the current stack frame (in which case the reference count would go away!)
It's worth noting that some of the inefficiencies associated with putting the reference count on the heap can be overcome by storing it "together" with the object itself. In boost, this can be accomplished by using boost::make_shared (for shared_ptr's) or boost::intrusive_ptr.
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