Share a pointer safely with C++20 std::atomic of std::shared_ptr
Swap a shared_ptr between threads without a data race using C++20 std::atomic<std::shared_ptr<T>>, supported by libstdc++ since GCC 12.
A std::shared_ptr has an atomic reference count, but the pointer object itself is not safe to read in one thread while another assigns it. C++20 adds a specialisation, std::atomic<std::shared_ptr<T>>, whose load and store are safe. It fits "read-mostly configuration": readers take a snapshot, the writer publishes a replacement, and the old object dies when the last reader drops it. GCC 12 or later, -std=c++20 -pthread.
#include <atomic>
#include <cstdio>
#include <memory>
#include <thread>
struct Config { int limit; };
std::atomic<std::shared_ptr<const Config>> cfg{
std::make_shared<const Config>(Config{1})};
int main()
{
auto snapshot = cfg.load();
std::printf("reader: %d\n", snapshot->limit);
std::thread w([] { cfg.store(std::make_shared<const Config>(Config{2})); });
w.join();
std::printf("reader: %d (old snapshot still %d)\n",
cfg.load()->limit, snapshot->limit);
}reader: 1
reader: 2 (old snapshot still 1)The snapshot keeps the first Config alive, so a reader that is mid-use never sees it freed. Making the pointee const means nobody mutates it after publication. The catch is that the specialisation is not lock-free: libstdc++ guards it with an internal lock, is_lock_free() returns false, and the older free functions std::atomic_load(&sp) are deprecated in C++20. See std::atomic<std::shared_ptr>.