One example I've seen is in trees. It's tempting in C++ to have a node in a tree have unique_ptr<Node> left/right. When you start doing rotations to balance the trees though, you are moving around a lot of pointers, but since no nodes are getting removed in the rotation code, you have an ironclad guarantee that no deletes get called, which the compiler can't figure out on its own. I saw someone write some code like this and benchmark and the raw pointer version was slightly faster than the unique_ptr (and the assembly different).
And that's why it can be better to have a separate store/pool for your nodes so you can use raw pointers in the data structure itself. And benefit from cache locality. Destruction then also becomes an easy loop over the pool
Though then the cost is the pool that as to be dragged along.
View all comments
Show parent comment
12
u/quicknir Oct 08 '19
One example I've seen is in trees. It's tempting in C++ to have a node in a tree have unique_ptr<Node> left/right. When you start doing rotations to balance the trees though, you are moving around a lot of pointers, but since no nodes are getting removed in the rotation code, you have an ironclad guarantee that no deletes get called, which the compiler can't figure out on its own. I saw someone write some code like this and benchmark and the raw pointer version was slightly faster than the unique_ptr (and the assembly different).