'Lifetimes of shared_ptr in a boost::circular_buffer

I am implementing a GHB PC/DC (Figure 6) prefetcher, and this contains a fixed-size hash-table mapping addresses to pointers in a circular buffer (aka fixed-size queue with FIFO semantics): enter image description here

Notice that each element in the circular buffer may not just be 'pointed to' by an entry in the index table, but is also part of a linked list containing (usually disjoint) elements within the global history buffer queue. Therefore, there are at least two, and up to three pointer owners here:

  • the buffer queue itself
  • the entry in the index table
  • (possibly) the preceding element in the linked list

Now, I have to manage the lifetimes of said pointers, because when an element in the circular buffer is evicted and overwritten when the latter is full, the destructor for said element is called, and ideally the pointer and the target data is deleted, all other references are set to nullptr, and problem solved.

However, I've thought about this both using raw *pointers, and std::shared_ptr, and there are still two (maybe more) dangling pointers owned by the index table, and the preceding element. Perhaps there is a gap in my knowledge, but I'm not sure how I can set these two pointers to nullptr to truly ensure correctness. What can I do here? Or is this unnecessary altogether?



Solution 1:[1]

It was a gap in my knowledge: std::weak_ptr exists to solve precisely this problem.

Now, if the buffer has std::shared_ptrs, and the index table and the 'next' pointers in the linked list nodes are std::weak_ptr, then there is only one owner, and the weak pointers are expired, which is nice.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SRSR333