Re: naked pointer vs boost::shared_ptr<T>
On Mar 2, 4:33 am, "Dejan.Mircev...@gmail.com"
On Mar 1, 5:10 am, "James Kanze" <james.ka...@gmail.com> wrote:
In my own applications, I find that most pointers are to objects
with explicit lifetimes, and I've yet to find a smart pointer
which is applicable to them (although I've tried).
Isn't any smart pointer with a reset() method applicable? The memory
owner can declare a smart instead of a naked pointer, and call reset()
instead of delete. Everything else would remain the same. The
advantage would be exception safety and a clear convention for who
owns the memory at any given time.
But what does that buy you over a raw pointer?
A fairly large percent of the time, such entity objects will be
referenced through some sort of map; they are known outside the
program, and of course, pointers don't work outside the program,
so they have some other identity key as well. In such cases,
one possible solution would be an
std::map< ExternalKey, boost::shared_ptr< ObjectType > >
To delete the object, the user (or the object itself) removes
itself from the map.
I find this solution a bit too subtle for my tastes. If the
object wants to delete itself, I find the intent far clearer if
the code says "delete this", rather than "registry.erase(
myId )" (statement which is then part of the destructor); it
seems to express the intent better: the object is being
destructed (and thus removed from the registry), rather than the
object is being removed from the registry (which incidentally
means that it's lifetime has ended). Note too that if you use
the registry.erase() method, the object might not be destructed
immediately; someone might still be using it somewhere, and hold
a shared_ptr to it as well. You need deterministic destruction,
and you aren't getting it.
James Kanze (GABI Software) email:firstname.lastname@example.org
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]