Search code examples
c++11nonblockinglock-free

invalid initialization of non-const reference of type ‘Node*&’ from an rvalue of type ‘std::atomic<Node*>::__pointer_type {aka Node*}’


I have the following snippet of code:

struct Node {
   int data;
   Node *next;
};

atomic<Node*> head;
atomic<Node*> temp1 = head.load();
..
Node *temp2 = new Node;
//initialise values
head.compare_exchange_strong(temp1, temp2);

However, I get the following error:

invalid initialization of non-const reference of type ‘Node*&’ from an rvalue of type ‘std::atomic::__pointer_type {aka Node*}’.

I am not getting which reference is constant here. Any help will be appreciated.


Solution

  • Simple answer is that temp1 should be a Node*, not an Atomic, as cmp/xchg takes two simple type variables.

    But I don't really understand what you are trying to achieve. Surely if you want next to be protected against threading, then it should be declared Atomic inside the struct?