tags:

views:

179

answers:

4

I'd like to reduce some visual noise in the code and hide shared_ptr behind a typedef like this:

typedef boost::shared_ptr<SomeLongClass> SomeLongClassPtr;

So this:

void foo(const boost::shared_ptr<SomeLongClass>& a,
         boost::shared_ptr<SomeLongClass>& b);

becomes this:

void foo(const SomeLongClassPtr& a, SomeLongClassPtr& b);

On the other hand I'm worried that I'm reducing the explicitness of the code.

Which is a better style?

+4  A: 

We use TypePtr typedefs in our code for shared_ptr<Type> objects. It is also useful to have a TypeConstPtr for shared_ptr<const Type>.

James McNellis
Ditto. If it improves readability and maintainability, it can hardly be a bad thing.
Jon Purdy
+4  A: 

Given that std::string is itself a typedef, I think you are fine. I do it myself.

Even Scott Meyers recommends typedef for ease of reading code in cases like yours.


EDIT: Effective C++, Second Edition, Page 120, Item 28, fourth paragraph. "...provide typedefs that remove the need..."

More Effective C++, 7th printing, Page 237, Item 31 First paragraph.

More Effective C++, 7th printing, Page 238, Item 31 First paragraph after code sample.


In essence, no worries. :-)

JustBoo
I'd love to have a Scott Meyers' reference to that, but meanwhile I'll take your word for it.
Alex B
@Alex, see edit above. :-)
JustBoo
+1  A: 

You might name the typedef 'SomeLongClassSharedPtr', which is both explicit and easy to type.

A negative consequence from this practice is that some autocomplete implementations (e.g. in Eclipse CDT) fail to follow through it. That hasn't stopped me personally from using it though.

Onestone
+1  A: 

I'm kind of opposed to typedefs that hide whether things are real pointers (or references), having seen too much unreadable C code that does this. But applying some casuistry, I guess shared_ptrs are not real pointers, and so the typedef is OK. But you are losing information - you can no longer tell just by looking at the function declaration (or definition!) what its semantics are.

anon
And let me guess, you are absolutely opposed to putting a "p" in front of it. That would smack of Hungarian Notation and we certainly can’t have any of that! I favor pragmatism over the herd mentality. And no, I don't use or condone HN. I will put a "p" in front of a pointer name on occasion though.
JustBoo
@JustBoo I've never been accused of following the herd before, but I suppose there is a first time for everything. And I do use a very limited for of Hungarian myself - all my member variables are prefixed with an 'm'.
anon
@Neil: Well alright then. :-D I do too. http://stackoverflow.com/questions/3461697/cstring-variable-name-prefix/3461766#3461766 coupled with the occasional "p" and that's it.
JustBoo