Re: Never ever use a raw pointer when a smart pointer can do the same
job
On Aug 14, 5:58 pm, Noah Roberts <roberts.n...@gmail.com> wrote:
Alf P. Steinbach wrote:
And for that you'd not change the 'adapter' pointer into a
smart pointer (it doesn't matter for the 'adapter' pointer,
it's just a case of personal preference),. You would instead
provide a higher level interface (inline in a header) that
gives the 3rd party application a smart pointer. So the
example is an example where a smart pointer would be useful,
but not as a simple replacement of the current raw pointer.
I totally agree with everything you just said. Simply
slapping a smart pointer on a raw pointer without thinking is
not a good approach. You should think about what the raw
pointer is for and then analyze what construct would best
smarten it up.
On the other hand, it's not going to harm anything to do it.
It may be unnecessary added complexity. I'll grant you that it
does provide a hook, a place where you can add extra checking if
needed. And could prevent some really stupid mistakes, like
e.g. incrementing a pointer which doesn't point into an array.
But such more or less transparent smart pointers don't seem to
be common; for better or worse, when people speak of "smart
pointers", they are almost always thinking of Boost::shared_ptr.
If your project actually has such smart pointers (e.g. a
navigation_ptr, or whatever, that doesn't have anything to do
with object lifetime management, other than, perhaps, checking
that the object is still alive when the pointer is
dereferenced), and your coding guidelines say to use these
(amongst other smart pointers), then I take back my objection to
them. My impression is, however, that when people propose rules
like "never use a raw pointer", this isn't what they have in
mind (but I'd be happy to be proven wrong).
If they're trying to get you to adhere to a standard in
development then even enforcing it in cases like this, though
they may seem pedantic and stupid, might be the best move on
their part.
In fact, one case an auto_ptr would help is if initialize is
called multiple times. Your code never actually checks to see
if it already exists, ergo you could get a memory leak if a
client program called the function repeatedly. An auto_ptr
would delete the previous reference and then accept the new
one...no leak.
But a loss of identity. This might be acceptable for an
immutable object, but even then, I'd prefer something more on
the lines of a singleton. (And of course, even if immutable, if
the value depends on some arguments to the constructor, if you
construct it twice, you might want to check that the arguments
are identical.)
--
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