How to call rvalue member function from another rvalue member function?

I am trying to create a class that should only exist temporarily. I use this to create an interface similar to partially applying a function. Here is a stupid example of what I'm trying to do.

struct Adder {
  explicit Adder(const int &leftOp)
    : leftOp(leftOp) {}

  int add(const int rightOp) const {
    return leftOp + rightOp;
  }

  //note that addTwice calls add
  int addTwice(const int rightOp) const {
    return add(rightOp) + add(rightOp);
  }

private:
  const int &leftOp;
};

struct Calculator {
  explicit Calculator(const int leftOp)
    : leftOp(leftOp) {}      

  Adder add() const {
    return Adder(leftOp);
  }

  void setLeftOp(const int newLeftOp) {
    leftOp = newLeftOp;
  }

private:
  int leftOp;
};

The calculator is used as follows.

Calculator myCalculator(4);
const int myNum = myCalculator.add().add(5);
std::cout << myNum << '\n'; // 9

I want to restrict the interface Adderso that it can only be called, as described above. I want the compiler to prevent users from storing Adderin a variable.

auto myCalcPtr = std::make_unique<Calculator>(4);
const Adder adder = myCalcPtr->add();
myCalcPtr.reset();
//oh dear. Adder has a dangling reference to a member in Calculator
const int myNum = adder.add(5);

My immediate thought was to note Adder::addand Adder::addTwicehow &&so:

int add(const int rightOp) && {
  return leftOp + rightOp;
}
int addTwice(const in rightOp) && {
  return add(rightOp) + add(rightOp);
}

but I got compiler errors in Adder::addTwice. The error was

No matching member function for call to `add`
Candidate function not viable: 'this' argument has type 'const Adder' but method is not marked const

So, I added that both functions const &&as such

int add(const int rightOp) const && {
  return leftOp + rightOp;
}
int addTwice(const in rightOp) const && {
  return add(rightOp) + add(rightOp);
}

, stackoverflow

Adder tempory?

, . !

+4

Source: https://habr.com/ru/post/1684660/


All Articles