Reading a raw ptr after all owning shared_ptrs are destroyed: is this undefined behavior?

61 Views Asked by At

I thought about this problem while removing nodes in a list in c++:

if I have a doubly linked list node that uses shared_ptr to hold references to adjacent nodes

struct Node {
    int data;
    std::shared_ptr<Node> next;
    std::shared_ptr<Node> prev;
}

If I remove a node from the list, but keep a raw ptr reference to it, like so:

Node* curr = randomNode.get();

if(curr->prev) {
    curr->prev->next = curr->next;
}
if(curr->next) {
    curr->next->prev = curr->prev;
}

process(curr->data);

Is the access of curr->data undefined behaviour? There surely is a chance that the memory has been freed because all ownership has been relinquished (adjacent nodes owned curr).

upon testing and debugging this function, the raw ptr is still pointing to valid memory with the correct data. It doesn't appear to be undefined behavior unless I am incorrectly destroying the owners.

0

There are 0 best solutions below