This discussion on memory leaks reminded me of something I wanted to ask a couple of days ago.
I've recently read on the Use Count technique to manage pointer data members. However, it confused me. Not so much how they are implemented, but more the why they are implemented.
And this is why; Assuming Ptr_class to be a class object that has a single pointer data member and that implements Use Count to manage this pointer...
The output is undefined. As soon as bla gets out of scope, the destructors of both bla and the use count class will make sure bla gets destroyed, but also that the free store gets freed.Code:int *value = new int(6); { Ptr_class bla(value); } std::cout << *value << std::endl;
1.
Why do I want this? At first glance, this seems to me an intrusive behavior of bla, considering that value's lifespan becomes dependant on Ptr_class. The owner of the free store object is the class user, not the class implementor.
2.
This technique forces any object of the Ptr_class to be defined based on the free store. If value is not defined on the free store, the above code throws a compile-time error. Doesn't this technique limit my use of this class?
3.
With each new pointer member being defined in Ptr_Class, the Use Count class needs to define another counter and another pointer. Isn't this excessive in terms of memory usage?
4.
With each new pointer member, the class copy control becomes increasingly bloated with code. Is this technique efficient?
I confess, Use Count didn't suit my fancy. But maybe I'm not seeing this correctly.