Hacker News new | ask | show | jobs
by aslmq 722 days ago
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.

2 comments

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.