The object is destroyed and its memory deallocated when either of the following happens:. This feature can be used to point to member objects while owning the object they belong to. The stored pointer is the one accessed by get , the dereference and the comparison operators. The managed pointer is the one passed to the deleter when use count reaches zero. This is sometimes used to keep a dynamic library or a plugin loaded as long as any of its functions are referenced:.
The managed object is constructed in-place in a data member of the control block. In this case, the control block stores a pointer to the managed object.
These pointers are not necessarily equal. If that counter reaches zero, the control block calls the destructor of the managed object. In existing implementations, the number of weak pointers is incremented [1] , [2] if there is a shared pointer to the same control block.
Create account Log in. The weak count does not play any role in deciding the lifetime of the managed object, which is deleted when the reference count reaches zero. However, the control block itself is not deleted until the weak count also reaches zero. The deleter is type-erased for two reasons.
Second, a deleter is a function object or a function pointer , e. The control block itself is allocated by an allocator that must satisfy the Allocator requirements.
When a custom allocator is not provided, the std::allocator is used that dynamically allocates the control block. The control block keeps a copy of the allocator, which is type-erased like the deleter. There are two ways to use a custom allocator. But under its simplicity lie extensive details that make it work. Nonetheless, for most applications, this cost is reasonable for automatic memory management.
Tutorial Mar 21, hkumar. How is the reference counting implemented? Does it use a doubly linked list? Btw, I've already googled, but I can't find anything reliable. Such aux class the actual name depends on the implementation is derived by a family of templatized classes parametrized on the type given by the explicit constructor, say U derived from T , that add:.
A smart pointer implementation could be deconstructed, using policy-based class design 1 , into :. Popular ownership strategies include: deep copy, reference counting, reference linking, and destructive copy.
Reference counting tracks the number of smart pointers pointing to owning 2 the same object. When the number goes to zero, the pointee object is deleted 3. The actual counter could be:.
Contained within the pointee object itself: intrusive reference counting. The disadvantage is that the object must be constructed a priori with facilities for counting:. Finally the method in your question, reference counting using doubly linked lists is called reference linking and it:. This leads to the idea of keeping an "ownership list" :.
0コメント