2

I am trying to create a std::shared_ptr type std::atomic variable. compile on online compiler

#include <iostream>
#include <memory>
#include <atomic>
//using namespace std;

class abc
{
public:
std::atomic <std::shared_ptr <int>> abl;
std::shared_ptr<int> a;  

void set(int x)
{
    abl.store(std::make_shared<int>(10) , std::memory_order_relaxed);
}

void out()
{
    a = abl.load(std::memory_order_relaxed);
    std::cout<< "value" << *a;
}
};

int main()
{
    abc ab;
    ab.set(10);
    ab.out();
    std::cout << "Hello World"; 

    return 0;
}

but getting following error

error: static assertion failed: std::atomic requires a trivially copyable type                                              
       static_assert(__is_trivially_copyable(_Tp), 

but when i tried it on my linux machine with complier version gcc 4.8(C++11) it compiled successfully but crashed.

i go through this and found shared_ptr is surely not TriviallyCopyable. compiler should give compile time error

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
vinit
  • 131
  • 2
  • 9
  • 4
    Prefer `atomic_shared_ptr` from C++17... – Kerrek SB May 23 '16 at 11:47
  • Interestingly, the standard just says *"The type of the template parameter T shall be trivially copyable"*. That's a requirement for the programmer, not for the compiler - so it *can* tell you that to be nice, but isn't required to. Also see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=63322 – Bo Persson May 23 '16 at 18:02

0 Answers0