Re: Never ever use a raw pointer when a smart pointer can do the same
job
On Aug 14, 6:34 pm, Noah Roberts <roberts.n...@gmail.com> wrote:
Hicham Mouline wrote:
... my colleague says.
I disagree on the "Never".
Opinions about this "rule of thumb" welcome.
regards,
I think there's some misunderstanding of what a standard like
this should look like by some posting and maybe by your boss
as well. It is 'generally' impossible to use smart pointers
for everything and not desired all the time either.
For example, try implementing a smart pointer without a raw
pointer. Sounds pretty stupid, doesn't it. Nieminen makes a
fairly similar demand though for it's a logical end of
"never". Although a linked list can be made with smart
pointers, it may not be the best approach. The more important
thing is to abstract the list in such a manner that you never
know or care that it's using pointers inside...or not.
Hey, we agree about something. At the lowest level, you can't
use smart pointers, because they're not implemented yet.
A better standard might tell you to not pass raw pointers out
of any public interface
I'm less sure about this. *IF* the public interface returns a
pointer to a dynamically allocated object, *AND* expects the
caller to take over lifetime management of this object, then I'd
strongly recommend using an std::auto_ptr for the return value.
But most of my functions which return pointers are more along
the lines of looking up an existing object. Logically, what
they're returning is a Fallible< T& >, a reference and not a
pointer, except that the function can fail to find the object.
And in my book, the "standard" implementation of Fallible< T& >
is T*; my Fallible class doesn't support instantiation over
reference types, and I've never been motivated to add such
support, given that T* works so well. (On the other hand...
fairly recently, I extended the class to handle error
codes---not only failure, but why. I haven't needed this
extension for "references" yet, but if I did, it's obvious that
T* won't suffice. So maybe Fallible< T& > is the correct
solution, even if, compared to a T*, it seems a bit over-complex
and heavy.)
and to prefer smart pointers internally as well. This allows
the developer to use raw pointers internally when they just
make the most sense but then none of this is exposed, which is
where most problems start.
More generally, public interfaces may require stricter
guidelines than internal implementation code. I think that's a
good point, often overlooked.
--
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