Pass by reference as rvalue

80 Views Asked by At

When I try to call the move member as pass by reference, the compiler throws an error but when I redefine the member function to pass by value, it works.

Can I not use pass by reference as an rvalue in my member function?

#include <iostream>
#include <string>

class Screen{
private:
    std::string contents;
    using position = std::string::size_type;
    position height,width,cursor_position;
public:
    Screen() = default;
    Screen& move(position&,position&); // Pass by reference
};

Screen& Screen::move(position& row,position& col)
{
    (*this).cursor_position = (row * width) + col;
    return *this;
}

int main() {
    Screen myScreen;
    myScreen.move(4,0); // This line gives a compile error
}
2

There are 2 best solutions below

0
On

No, rvalue cannot be passed as non-const lvalue reference. It can be passed as const lvalue reference though because the compiler will create a temporary to point the lvalue to.

2
On
int main() {
    Screen myScreen;
    position rowTmp = 4;
    position colTmp = 0;
    myScreen.move(rowTmp,colTmp); 
}

Try it!

You need to create two real variables for 'Pass by refrrence'.