For the past few years, I’ve generally accepted that
if I am going to use ref-counted smart pointers
invasive smart pointers is the way to go
—
However, I’m starting to like non-invasive smart pointers due to the following:
- I only use smart pointers (so no Foo* lying around, only Ptr)
- I’m starting to build custom allocators for each class. (So Foo would overload operator new).
- Now, if Foo has a list of all Ptr (as it easily can with non-invasive smart pointers).
- Then, I can avoid memory fragmentation issues since class Foo move the objects around (and just update the corresponding Ptr).
The only reason why this Foo moving objects around in non-invasive smart pointers being easier than invasive smart pointers is:
In non-invasive smart pointers, there is only one pointer that points to each Foo.
In invasive smart pointers, I have no idea how many objects point to each Foo.
Now, the only cost of non-invasive smart pointers … is the double indirection. [Perhaps this screws up the caches].
Does anyone have a good study of expensive this extra layer of indirection is?
EDIT: by smart pointers, I may be referring to what others call “shared-pointers”; the whole idea is: there is a reference-count attached to objects, and when it hits 0, the object is automatically deleted
There are several important difference between invasive or non-invasive pointers:
The biggest advantage of second (non-invasive):
shared_ptr/weak_ptr).Advantage of first is when you need to get smart pointer on this (at least in case of
boost::shared_ptr,std::tr1::shared_ptr)shared_ptrfrom this in constructor and destructor.