代码
struct CustomReal
{
private real value;
this(real value)
{
this.value = value;
}
CustomReal opBinary(string op)(CustomReal rhs) if (op == "+")
{
return CustomReal(value + rhs.value);
}
bool opEquals(ref const CustomReal x) const
{
return value == x.value; // just for fun
}
}
// Returns rvalue
CustomReal Create()
{
return CustomReal(123.123456);
}
void main()
{
CustomReal a = Create();
assert(a == CustomReal(123.123456)); // OK. CustomReal is temporary but lvalue
assert(a == Create()); // Compilation error (can't bind to rvalue)
assert(a != a + a); // Compilation error (can't bind to rvalue)
}
编译错误
prog.d(31): Error: function prog.CustomReal.opEquals (ref const const(CustomReal) x) const is not callable using argument types (CustomReal)
prog.d(31): Error: Create() is not an lvalue
问题:
- 为什么
const ref
不能绑定到右值?可以吗? - 我需要返回
ref CustomReal
或返回const ref CustomReal
来opBinary()
解决这个问题吗?可以吗? - 返回对在堆栈上创建的本地对象的引用是否正确?
ref CustomReal Create() { return CustomReal(0.0); }