Search code examples
c++pointersnullptr

Atomically exchange pointer with nullptr


How can I do the following operations in single atomic operation? Is that possible?

 LARGE_INTEGER* ptr; // field

 void method()
 {
       LARGE_INTEGER* local = ptr;
       ptr = nullptr;
 }

So I want to store pointer from field into local pointer and immediately set that field to nullptr.

In other words, I want to move pointer from field into local variable in single atomic operation.


Solution

  • Since C++11 you can use std::atomic for this purpose like this:

    #include <atomic>
    LARGE_INTEGER value;
    std::atomic<LARGE_INTEGER*> ptr{&value};
    LARGE_INTEGER* local = ptr.exchange(nullptr);