1

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
}
StenSoft
  • 9,369
  • 25
  • 30
  • What language is this? What does the version of the code that doesn't work look like? What does it mean to "call a member as pass by reference"? – Scott Hunter Aug 05 '15 at 01:38
  • You shouldn't accept parameters by non-const reference unless the function intends to modify the parameter – M.M Aug 05 '15 at 02:32

2 Answers2

5

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.

StenSoft
  • 9,369
  • 25
  • 30
1
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'.

Albert
  • 29
  • 1
  • 5
  • Please add some explanation to help the questioner; your code does seem to fix his problem, but on its own it is not really useful. – Ken Y-N Aug 05 '15 at 02:18
  • Thank you for your suggestion.@ Ken Y-N.I will pay attention to this issue in the future. – Albert Aug 05 '15 at 02:31