Yannick Tremblay writes:
In article <firstname.lastname@example.org>,
Sam <email@example.com> wrote:
That's what Boost's shared_ptr does. Although -- much like the rest
of Boost's code -- it is horribly inefficient, and suffers from
certain design flaws -- it is often a good starting point for your
own reference-counted pointers.
Then don't. Resist the temptation to use Boost as long as you can.
Many years from now, you'll be thankful for that. Define and
implement your own pointer class, and use this as a learning
experience. True, your reference counting implementation will be much
slower than Boost's. Boost does not use mutexes for this, rather it
uses CPU-specific atomic increment/decrement instructions (and gets
it partially wrong, by the way). But this is a good way to learn some
important principles of thread-safe programming.
Care to clarify?
The entire design is completely braindead. A separate object, a tiny
object that holds the reference count, gets instantiated for every
object tracked by shared_ptr. This is insane. Heavy use of shared_ptr is
just going to hammer your heap like there's no tomorrow. This is
horrible design. The correct approach is to store the reference count in
superclass and derive from it. You can't then attach shared_ptr to an
arbitrary libstdc++ object, of course, so you just multiply-inherit from
it. How hard is that?
Then you have the shared_ptr itself, an object that holds two pointers,
one to the original object, the other to the reference count.
Which means that most compilers won't be able to hold a shared_ptr in
CPU registers, like ordinary pointers. Instead, things are going to get
tossed around in memory.
There are also several other design flaws as well. Like the fact that
each time a reference count gets updated, it involves a call to a
library function. Reference count increment/decrement cannot be inlined,
due to a real first class fookup in the templates. After I read through
the class definition, I just shook my head, laughed, then quickly coded
my own reference-counted object implementation, and ended up
benchmarking it 15% faster than Boost's disgusting implementation.
A: Because it messes up the order in which people normally read text.