D中的const ref和rvalue

Sta*_*tas 5 d ref rvalue

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)
}
Run Code Online (Sandbox Code Playgroud)

编译错误

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
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/O8wFc

问题:

  1. 为什么const ref不能绑定到右值?好吗?
  2. 我需要返回ref CustomRealconst ref CustomRealopBinary()解决这个问题?好吗?
  3. 返回对堆栈上创建的本地对象的引用是否正确? ref CustomReal Create() { return CustomReal(0.0); }

Jon*_*vis 4

ref和之间的唯一区别const ref是“const ref是”constref“不是”。两者都必须带有一个变量。两者都不能临时。这与 C++ 不同,C++const T&会采用任何类型的值T- 包括临时值。

opBinary无法返回refor const ref,因为没有变量可返回。它正在创建一个临时的。也同样如此Create。使用您想要返回的值创建局部变量也没有帮助,因为您无法返回对局部变量的引用。它最终会引用一个不再存在的变量。

您需要在这里做的是添加另一个重载opEquals

bool opEquals(CustomReal x) const
{
    return value == x.value; // just for fun
}
Run Code Online (Sandbox Code Playgroud)

这样,您的代码就可以编译了。

但我要指出的是,目前的情况opEquals 确实需要解决一下。您会注意到,如果您只有我给您的重载opEquals,而不是您当前拥有的重载,则代码将无法编译,并且您会收到类似于以下内容的错误:

prog.d(15): Error: function prog.CustomReal.opEquals type signature should be const bool(ref const(CustomReal)) not const bool(CustomReal x)
Run Code Online (Sandbox Code Playgroud)

编译器目前对 for 结构的确切签名过于挑剔opEquals(其他一些函数 - 例如toString- 也有类似的问题)。这是一个已知问题,可能会在不久的将来得到解决。但是,现在只需声明opEquals. 如果将 aCustomReal与变量进行比较,则将const ref使用该版本,如果将 aCustomReal与临时变量进行比较,则将使用另一个版本。但如果你两者都有,那就没问题了。

现在,为什么

assert(a == CustomReal(123.123456));
Run Code Online (Sandbox Code Playgroud)

作品,以及

assert(a == Create());  
Run Code Online (Sandbox Code Playgroud)

没有,我不确定。我实际上预计它们都会失败,因为这不能暂时进行,但出于某种原因,编译器在这里接受它 - 它可能与它如何对待特殊const ref有关。opEquals无论如何,正如我所说,有一些问题和opEquals结构需要解决,希望这很快就会发生。但与此同时,声明两个重载opEquals似乎可以解决问题。

编辑:看来原因是

assert(a == CustomReal(123.123456));
Run Code Online (Sandbox Code Playgroud)

作品,以及

assert(a == Create());
Run Code Online (Sandbox Code Playgroud)

不是因为这样的事实(出于我不明白的原因)结构文字被视为左值,而不是的函数的返回值ref(毫不奇怪)是右值。有几个与之相关的错误报告,认为结构文字应该是右值,但显然它们是设计好的左值(这让我感到困惑)。无论如何,这就是为什么 take 函数只能const ref与结构体文字一起使用,但不能与函数的返回值一起使用。