Re: C++ Primer 4th edition Reference Counting Smart Pointers
Are there hidden problems with the RCSP code in C++ Primer 4th ed that
I have never seen the smart pointer implementation in C++ Primer, but
I do agree that creating a good smart pointer class is a very
non-trivial problem. There are all kinds of safety and usability (and to
a lesser extent, efficiency) concerns which are often hard or laborious
Basically small pointers usually attempt to emulate regular pointers
as far as possible, but adding reference counting to the mix in order to
automate object destruction. However, regardless of all the syntactical
tools available in C++, it's still very hard, if not outright
impossible, to make a class fully emulate a pointer.
The most obvious case is that a pointer can point to either an
individual object or an array, and deleting is different in those cases.
(Of course one could argue that it's a *good* thing that smart pointers
to objects and smart pointers to arrays are kept separate and mutually
Then there's the question of inheritance: A pointer of one type can
point to an object of another, inherited type. Pointers pointing to
different types like this can be assigned to each other. Moreover, you
can cast (statically or dynamically) a pointer of base class type to a
pointer of derived class type. A smart pointer desiring to emulate
regular pointers would need to address these issues.
A pointer can point to an incomplete type. Making a smart pointer
correctly support incomplete types is possible, but not glaringly
obvious. (Except in the case of intrusive smart pointers, for which it's
just not possible.)
An object might have been allocated with something else than the
default system allocator. Many naive smart pointer implementations out
there don't support deallocation using that same special allocator.
(Also, most don't support allocating their own ancillary data using a
user-specified allocator, rather than the default system allocator. I
think even the boost smart pointers don't support this.)
Most naive smart pointer implementations are not thread-safe. Making a
smart pointer thread-safe efficiently is extremely difficult.
Making a smart pointer safe to use is extremely difficult, if not
impossible. It's basically impossible to make sure that the same pointer
is not given to two different (non-instrusive) smart pointers. Or that a
pointer to something not allocated with 'new' is not given to it.
Intrusive smart pointers have their own gotchas, most of which naive
implementations get wrong. (For example most of them fail to take into
account that objects might be directly assigned to other objects, which
can mess up the reference counter if not specifically taken into account.)