Hacker News new | ask | show | jobs
by account42 722 days ago
shared_ptr isn't the only smart pointer and definitely shouldn't be used for everything. The default should be unique_ptr which is simple to reason about and a huge improvement over only having raw pointers that may or may not be owning what they point to.
1 comments

unique_ptr is often too restricted. If you have a simple tree with unique_ptr, already the back edges need to be raw pointers to avoid cycles.

If you add an iterator, the iterator needs internal pointers to the nodes, so by definition the node pointers are not unique. Again, raw pointers are better.

I have never seen a complex data structure where unique_ptr is really used.

Yes, smart pointers don't mean you can entirely stop thinking about ownership and lifetimes but they let you express that ownership in an explicit way with some compiler-enforced protections against mistakes.

> I have never seen a complex data structure where unique_ptr is really used.

What's a "complex" data structure? Anyway, I'd expect to see unique_ptr more in user code rather than in library implementations of data structures where where relatively minor concerns might warrant an ad-hoc implementation even if you could use unique_ptr. In many cases it's probably just that the implementations precede the standardized smart pointers.

You can just not point back to parents (which is rarely needed for anything but iterators) and to not use iterators (since they're a pain in the first place!). The visitor pattern exists for a reason.