Home > Enterprise >  cannot bind non-const lvalue reference of type 'Node&' to an rvalue of type 'const No
cannot bind non-const lvalue reference of type 'Node&' to an rvalue of type 'const No

Time:03-28

I am trying to implement a linked list with struct but i have a problem. I get this error when i try to delete the node. Can someone please help me?

struct Node {
    int value;
    Node *previous;
    Node *next;
};
// *current_node in all functions is a random address of a node in the linked list 
Node get_node(size_t position, Node *current_node){
    while (current_node->previous){
        current_node = current_node->previous;
    }
    for (int i = 1; i < position; i  ){
        current_node = current_node->next;
    }
    return *current_node;
}

void delete_node(Node &node, Node *current_node){
    while (current_node->previous){
        current_node = current_node->previous;
    }
    while (current_node->next){
        if (current_node == &node){
            node.previous->next = node.next;
            node.next->previous = node.previous;
            node.next = nullptr;
            node.previous = nullptr;
        }
        current_node = current_node->suivant;
    }
}

int main(){
    Node node1 = {11, nullptr, nullptr}; // works fine  
    Node node2 = {22, nullptr, nullptr}; // works fine
    add_end(node2, &node1); // works fine
    delete_node(get_node(2, &node1), &node1); // bug is here
}

CodePudding user response:

The problem is that the function delete_node has its first parameter as a reference to non-const Node while the function get_node returns a Node by value. This means that the call expression get_node(2, &node1) is an rvalue. But since, we cannot bind a reference to non-const Node to an rvalue of type Node, you get the mentioned error.

One way to solve this is to change the return type of get_node to Node& as shown below:

//--vvvvv------------------------------------------------>return type changed to Node&
    Node& get_node(size_t position, Node *current_node){
        //other code as before
        return *current_node;
    }
  • Related