コード
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); }