D 中的 const ref 和右值

发布于 2024-11-28 15:32:40 字数 1321 浏览 1 评论 0原文

代码

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

http://ideone.com/O8wFc

问题:

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

Code

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)
}

Compilation error

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

http://ideone.com/O8wFc

Questions:

  1. Why const ref can't bind to rvalue? Is it ok?
  2. Do I need to return ref CustomReal or const ref CustomReal from opBinary() to fix this problem? Is it ok?
  3. Is it correct to return a reference to local object created on stack?
    ref CustomReal Create() { return CustomReal(0.0); }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白况 2024-12-05 15:32:40

refconst ref 之间的唯一区别是 const refconstref > 不是。两者都必须带有一个变量。两者都不能临时。这与 C++ 不同,其中 const T& 将采用 T 类型的任何值 - 包括临时值。

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

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

bool opEquals(CustomReal x) const
{
    return value == x.value; // just for fun
}

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

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

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

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

现在,

assert(a == CustomReal(123.123456));

为什么有效,为什么

assert(a == Create());  

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

编辑: 看来

assert(a == CustomReal(123.123456));

有效和

assert(a == Create());

无效的原因是因为(由于我不明白的原因)结构文字被视为左值,而 a 的返回值不是 ref 的函数(不出所料)是一个右值。有夫妇与其相关的错误报告,认为结构文字应该是右值,但显然它们是设计时的左值(这让我感到困惑)。无论如何,这就是为什么采用 const ref 的函数只能使用结构体文字,但不能使用函数的返回值。

The only difference between ref and const ref is that const ref is const and ref is not. Both must take a variable. Neither can take a temporary. This is different from C++ where const T& will take any value of type T - including temporaries.

opBinary cannot return either ref or const ref, because there's no variable to return. It's creating a temporary. The same goes for Create. And creating a local variable with the value that you want to return doesn't help either, because you can't return a reference to a local variable. It would end up referring to a variable which didn't exist anymore.

What you need to do here is add another overload of opEquals:

bool opEquals(CustomReal x) const
{
    return value == x.value; // just for fun
}

With that, your code will compile.

I would point out though that the current situation with opEquals does need to be ironed out a bit. You'll notice that if you only have the overload for opEquals that I gave you and not the one that you currently have, the code fails to compile, and you get an error similar to this:

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

The compiler is currently overly picky about the exact signature of opEquals for structs (a few other functions - such as toString - have similar issues). It's a known issue and will probably be resolved in the near future. However, for now, just declare both overloads of opEquals. If you compare a CustomReal with a variable, then the const ref version will be used, and if you compare a CustomReal with a temporary, then the other version will be used. But if you have both, you should be okay.

Now, why

assert(a == CustomReal(123.123456));

works, and

assert(a == Create());  

doesn't, I'm not sure. I'd actually expect both of them to fail, given that const ref can't take a temporary, but for some reason, the compiler accepts it here - it probably has to do with how it treats opEquals special. Regardless, as I said, there are some issues with opEquals and structs which need to be ironed out, and hopefully that'll happen soon. But in the meantime, declaring both overloads of opEquals seems to do the trick.

EDIT: It appears that the reason that

assert(a == CustomReal(123.123456));

works, and

assert(a == Create());

doesn't is because of the fact (for reasons that I don't understand) a struct literal is considered an lvalue, whereas the return value of a function which is not ref is (unsurprisingly) an rvalue. There are a couple of bug reports related to it, arguing that struct literals should be rvalues, but apparently they're lvalues by design (which baffles me). In any case, that's why a function which takes const ref works with a struct literal but not with the return value of a function.

反话 2024-12-05 15:32:40

#1:是的,const ref 不能绑定到右值。 Andrei 认为在 C++ IIRC 中允许这样做是一个坏主意。
http://digitalmars.com/d/archives/digitalmars/D/const_ref_rvalues_103509 .html#N103514

奇怪的是结构文字在 D2 中算作左值,因此这是可行的:

struct A {}
void foo(ref A a) {}
void main()
{
    foo(A());
}

而调用以下方法则不行:

static A bar()
{
    return A();
}

foo(bar());

#1: Yep, const ref can't bind to rvalues. Andrei thinks it was a bad idea to allow that in C++ IIRC.
http://digitalmars.com/d/archives/digitalmars/D/const_ref_rvalues_103509.html#N103514

The weird thing is struct literals count as lvalues in D2, so this works:

struct A {}
void foo(ref A a) {}
void main()
{
    foo(A());
}

while calling the following doesn't:

static A bar()
{
    return A();
}

foo(bar());
糖果控 2024-12-05 15:32:40

对于#2(以及扩展#3):不,那是无效的,因为它必须是对刚刚超出范围的对象的引用。

For #2 (and by extension #3): No, that would be invalid as it would have to be a reference to an object that had just gong out of scope.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文