Why not just use a static variable as a reference counter for a smart pointer

When I check the "improved" version of the smart pointer, I need to increase the reference count. I see that they use some “sophisticated” methods for link counting, for example. a completely separate class or pointer pointing to an integer.

Here is one example:

template<class T> class SmartPointer{ T* mp_T; unsigned int * mp_Count; public: ... all the APIs ... }; 

I wonder what is a win? Since the goal is for all instances to share the value, why not just declare it as a static member variable:

 template<class T> class SmartPointer{ T* mp_T; static unsigned int m_Count; public: ... all the APIs ... }; 

I need to skip something, but after some searching, I can not find the answer. Enlighten the light.

+4
source share
4 answers

A static data member is used by all instances of the same class. But two different smart pointers should not use the same reference counter. Take an example

 SmartPointer<int> a; ... SmartPointer<int> b; SmartPointer<int> c = b; // ref count increased due to copying. 

In your schema, a m_Count will also be increased in the comments because the static variable is common to all SmartPointer<int> , although this line is not related to a .

+10
source

The idea is not that "all instances share the meaning." What made you think so?

The idea is that all pointer instances point to the same object for sharing the counter. And pointer instances pointing to different objects must have independent non-common counters. A static counter does not implement this concept.

+5
source

In a typical use case, there would be several objects , with one or more common pointers pointing to each object.

Using a static counter will not allow you to have multiple objects, as there will be only one reference counter.

+1
source

The goal is not that all instances of SmartPointer<T> share the same value for the entire process. Instead, the goal of multiple instances of SmartPointer<T> is to share the same value. There may be multiple instances of T* for which multiple smart pointers matter. for instance

 SmartPointer<MyType> sp1 = new MyType(); SmartPointer<MyType> sp2 = new MyType(); 

Having a static counter here would incorrectly relate the lifetime of two completely independent MyType values.

+1
source

Source: https://habr.com/ru/post/1379343/


All Articles