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.
The counter has to be shared with other instances of
SmartRefCountPointerwhich point to the same object.The whole point of ref-counted pointers is that there is a single place keeping track of how many references there are. This single place must thus be a global variable, or a location on the heap. The implementation you show has chosen for the later.