Re: shared_ptr and incomplete types
James Kanze wrote:
On the other hand, they are invasive;
the object being pointed to must know about them (typically be
deriving from a common base class---virtually, if the hierarchy
is open). Which means no reference counted pointers to existing
classes, nor to non-class types. For a "standard" pointer,
that's pretty much a killer exclusion.
I wonder if the language couldn't be enhanced so that you can allocate
existing objects and non-class types in such a way that the compiler
will internally make the allocation larger by sizeof reference counter
and then a special internal shared pointer can be used to manage objects
of this type.
Perhaps something like:
shared SomeClass* ptr = shared_new SomeClass();
That 'ptr' would be of the same size as a regular pointer. The memory
amount allocated by 'shared_new' would be sizeof(size_t) (or whatever)
larger than the memory allocated by the equivalent 'new'.
The semantics could perhaps be so that these would be erroneous:
shared SomeClass* ptr = new SomeClass(); // error
SomeClass* ptr = shared_new SomeClass(); // error
shared SomeClass* ptr = shared_new SomeClass();
shared SomeClass* ptr2 = ptr; // Ok
SomeClass* ptr3 = ptr; // error
SomeClass* ptr = new SomeClass();
shared SomeClass* ptr2 = ptr; // error
This can become a major issue if you are, for example, creating an
array of millions of shared_ptrs.
Yes, but is there ever any reason to have a container of
shared_ptr?
For example if you want a vector containing different types of objects
(which all have been derived from a common base class) and want the
memory taken by those objects be managed.