Hacker News new | past | comments | ask | show | jobs | submit login

shared_ptr: 1) It might be helpful to show an example with a bare pointer and then show the improved version with shared_ptr. 2) One good way to illustrate object lifetimes in RAII demos is to create a class that prints a message in the destructor. 3) In practice most people use a typedef for shared_ptr types. Instead of writing "shared_ptr<Class>" everywhere you would "typedef shared_ptr<class> ClassP" and then just use ClassP to declare shared_ptr variables.

auto: I think you can expand a bit on how auto interacts with reference and const qualifiers.




Three additional things I would add to the shared_ptr article:

1) Don't use shared_ptr for dynamic arrays (shared_ptr<T>(new T[n])).

2) Introduce use_count. That will explicitly show how shared_ptr does its magic.

3) It's almost always a good idea to treat shared_ptr<T> as a value type, not a reference type. There is very rarely a good reason to take a reference to a shared pointer since taking a reference, you know, actually creates a reference, but doesn't increase the reference count. As a corollary of this, arguments to a function should generally pass shared_ptr<T>, not shared_ptr<T>&.


Thanks for the feedback.

The first two points you mention are already on my mind for another article on shared_ptr when I revisit it (after doing a simple introduction to unique_ptr and weak_ptr). The third one I never considered to mention since I never considered using a reference to a shared_ptr but I realise that folks might consider it and should be warned against it. I'll make sure I point that out in the next one on shared_ptr.


Thanks for the feedback.

I have received this feedback regarding shared_ptr from multiple people - to show bare pointer version vs shared_ptr example. I'll add that soon.

Also, you are the second person to mention that there may need to be more content regarding auto with 'const' and '&'. I'll consider elaborating upon that too.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: