I am trying to make a system for lazy evaluation, however it seems my system wont work with rvalues/temporary variable. for example
class Number;
class LazyAddition
{
public:
Number& lhs;
Number& rhs;
LazyAddition(Number& lhs, Number& rhs)
: lhs(lhs), rhs(rhs)
{
}
LazyAddition(Number&& lhs, Number&& rhs)
: lhs(lhs), rhs(rhs)
{
}
};
class Number
{
public:
Number(int x)
: x(x)
{
}
LazyAddition operator+(Number& rhs)
{
return LazyAddition(*this, rhs);
}
Number(LazyAddition lazy)
{
x = lazy.lhs.x + lazy.rhs.x;
}
private:
int x;
};
It works fine when passing in lvalues like
Number num1(3)
Number num2(4)
LazyAddition { num1, num2 }
it also function when passing in rvalues
LazyAddition { Number(3), Number(4) }
however after the constructor is called, the number rvalues are immediately destroyed. this is problematic since I have references to them. I thought assigning the rvalue reference to the lvalue reference in the LazyAddition constructor might expand the lifetime, but it doesn't. is there any way to achieve this, or a better way to not copy rvalues?