Re: Never ever use a raw pointer when a smart pointer can do the
same job
* 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.
It's an old idea. I once, many years ago, communicated with DDJ about writing an
article about this, but nothing more came of it than a tentative first attempt.
I don't know exactly why: the policy of DDJ seems to be to cut communication
when they're not interested (I think there was a fundamental change in DDJ when
they took up former Object Magazine, a wishy-washy buzzword publication, and
I'm not even sure that DDJ is still published in hard-copy, I haven't seen it
for ages). Anyway, those who are interested can find implementations on the net.
E.g. I posted a very limited implementation in this group just a few days ago.
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.
However, files and socket objects and such, I think that's the proper usage. 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.
Cheers,
- Alf