Search code examples
c++shared-ptratomiccompare-and-swap

shared_ptr's std::atomic_compare_exchange_strong comparing with raw pointer


Is it possible in shared_ptr's atomic_compare_exchange_strong to compare with raw pointer?

Like so:

    struct Chunk{
       // atomics
       std::shared_ptr<Chunk> prev;
       std::shared_ptr<Chunk> next;
    };

    // chunk is guaranteed to stay alive while this operation
    void remove_chunk(Chunk* chunk){
        std::shared_ptr<Chunk> prev = std::atomic_load(&chunk->prev);
        std::shared_ptr<Chunk> next = std::atomic_load(&chunk->next);

        // Can I do this?
        std::shared_ptr<Chunk> self{chunk};
        std::atomic_compare_exchange_strong(&prev, &self, next);

        ...
    };

I thought about this, because http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_cmp says that compared only raw pointers. But is this required by standart, or just optimisation side-effect?

The question is only about atomic_compare_exchange_strong correctness.


Solution

  • Almost certainly, this is wrong. In remove_chunk(Chunk* chunk), chunk is probably just identifying the chunk to remove. In std::shared_ptr<Chunk> self{chunk};, you imply that you were the owner of chunk, and self becomes the new owner.