0

Passing an Rvalue into a copy constructor or assignment operator seems to me to be a very important thing to be able to do. For example:

int a = b+c;

or

int a;
a = b+c;

Without this it would be hard to do math calculations.
Yet I am unable to do this with a class. Here's my code

#include <iostream>

using namespace std;

struct node{
public:
    node(int n){
        node* ptr = this;
        data = 0;

        for (int t=0; t<n-1; t++){
            ptr -> next = new node(1);
            ptr = ptr -> next;
            ptr -> data = 0;
        }

        ptr -> next = NULL;
    }
    node(node &obj){
        node* ptr = this;
        node* optr = &obj;
        while (true){
            ptr -> data = optr -> data;
            optr = optr -> next;
            if (optr == NULL) break;
            ptr -> next = new node(1);
            ptr = ptr -> next;
        }
    }
    void operator=(node &obj){
        delete next;
        node* ptr = this;
        node* optr = &obj;
        while (true){
            ptr -> data = optr -> data;
            optr = optr -> next;
            if (optr == NULL) break;
            ptr -> next = new node(1);
            ptr = ptr -> next;
        }
    }
    ~node(){
        if (next != NULL) delete next;
    }


private:
    double data;
    node* next;
};

node func1(){
    node a(1);
    return a;
}

void func2(node a){
    node b(1);
    b = func1();
}



int main(){
    node v(3);
    func1();
    func2(v);
}

I am given this compiling error:

expects an l-value for 1st argument

how can I write a copy constructor and assignment operator that take r-values as well as l-values?

Thanks for the help

Mathew
  • 1,116
  • 5
  • 27
  • 59
  • 1
    Whats wrong with a move-constructor and -assignment operator? – tkausl Sep 14 '16 at 01:59
  • "how can I write a copy constructor and assignment operator that take r-values as well as l-values?" You don't. You just implement one for each. `node(const node &obj)` and `node(node &&obj)` - same for assgn. Note the `const` for the copy constructor. Don't forget to let the `&&obj` in a destructable state after you are moving its content. – Adrian Colomitchi Sep 14 '16 at 02:20

1 Answers1

0

You are misusing the copy c'tor and assignment operator to achieve a move. Conventionally, copy c'tors and assignment operators receive const references, which can bind to both r-values and l-values. However, if you'd like to achieve a move, then use the move c'tor and assignment operator:

node(node&& n){ /* pilfer 'n' all you want */ }
node& operator=(node&& n) { /* ditto */ }

Conflating move semantics with copying only causes woe later on.

KyleKnoepfel
  • 1,426
  • 8
  • 24