Search code examples
c++c++11stdatomic

Atomic store throwing error


I recently upgraded to a C++11 compatible compiler, and I was trying to update some code from boost to c++11 standards. I ran into a problem when converting some code using atomic_store over. Here is some simple test code that seems to be throwing a compiler error for me.

int main()
{
    std::shared_ptr<int> m = std::make_shared<int>();
    *m = 1;

    std::shared_ptr<int> a =  std::make_shared<int>();
    *a = 2;

    std::atomic_store(&m,std::move(a));

    std::cout << *m << std::endl;
}

the std::atomic_store(&m,std::move(a)); line is throwing a compiler error for me:

'std::shared_ptr<int>' is not derived from 'volatile std::atomic<_ITp>'
     std::atomic_store(&m,std::move(a));
                                      ^

Has the way atomic_store changed when moving from boost to C++11? Do I now need to create an atomic object of a shared pointer?


Solution

  • The following code compiles fine with Clang 3.5:

    #include <memory>
    int main()
    {
        std::shared_ptr<int> foo, bar;
        std::atomic_store(&foo, bar);
    }
    

    However, it doesn't compile with GCC 4.9. The above code prints an error message, that atomic_store is not a member of std. If I also include <atomic>, the compiler prints the error message, that is shown in the question.

    Apparently, GCC 4.9 does not support atomic operations for std::shared_ptr. See also the documentation of libstdc++:

    20.7.2.5 | shared_ptr atomic access | Partial