While going through some of implementation for reference counting smart pointers, i found this type of implementation.
template<typename Type>
class SmartRefCountPointer{
Type* obj;
size_t* count; // <<--- Why pointer/ why is count on heap
}
Can you explain why this counter is moved to heap and not on stack? i would really appreciate if you can give any fail case.
All
SmartRefCountPointer
s that point to the same object should also update the same counter. That's why you cannot keep the counter as a member of smart pointer class and have to use a pointer (or reference) to it that can be passed to new smart pointer on copy. It is normally allocated by the first instance of smart pointer that is contructed with an object pointer (or contructs it itself) and deleted when reference count drops to zero.