Re: Never ever use a raw pointer when a smart pointer can do the same
job
On Aug 14, 2:12 pm, "Alf P. Steinbach" <al...@start.no> wrote:
* James Kanze:
Conceivably, there would be a use for a smart pointer which
works the opposite of garbage collection---deleting the
object causes the pointer to be null'ed. My site (when it
was accessible) had a ManagedPtr for that. In practice,
however, this is really only useful for 1->{0,1}
relationships, and not always for those (the object
containing the pointer often has to react to the fact that
the pointed to object has disappeared); I don't think I've
used this smart pointer more than once or twice in the more
than ten years since I implemented it.
It would be nice if objects that may encounter "unrecoverable
failures" were only accessible via such smart pointers.
The smart pointer would do all the validity checking, e.g.
instead as with current iostreams where every iostream
operation checks the state and possibly chooses to do nothing,
the smart pointer would centralize the checking and throw an
exception.
I more or less agree, although I'm not sure that the results
would be considered a "smart pointer". Maybe a decorator. (The
sentry objects are nice, as far as they go, but they really
don't go far enough. In my xdrstream code, I used some small
helper objects for accessing bytes; not only did they ensure
that the error codes were correctly set, they also allowed me to
use intelligible names, instead of sgetc (which only peeks, and
doesn't get) and such:-).
But whereas I once saw GUI widgets (which are generally
self-destroying) as a main usage for such a pointer, I now
hold the view that they're better accessed simply via raw
pointers. For the cases where a checking smart pointer would
detect access after destruction, are very few. In the majority
of cases, for a GUI widget the checking smart pointer would
just be added complication.
Once again, I totally agree.
However, files and socket objects and such, I think that's the
proper usage.
But why pointers? In practice, my file and socket objects all
either have local scope, or are part of a bigger object which
either has local scope or a specific lifetime (or in exceptional
cases, like a logger, has static lifetime).
For in contrast to GUI widgets these kinds of objects suffer
from having natural zombie states, states where nearly all
operations are invalid. A checking smart pointer can then
centralize and enforce the validity (non-zombie) checking.
OK. That's an interesting idea.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34