non-const method permitted on rvalue?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Oct 24 08:26:08 PDT 2014


On 10/24/14 10:49 AM, Shriramana Sharma via Digitalmars-d-learn wrote:
> Hello. I realize the wording "non-const method" is probably a C++-ism
> but please see the following code. In both C++ and D, the compilers
> are complaining only when I try to assign directly to the member of an
> rvalue, but if I try to assign via a non-const ref returned by a
> non-const method, then it's apparently fine?!! At least shouldn't D
> prohibit this? [Yet another case of rvalue refs being allowed to
> escape?]
>
> nonconst.d:
> --
> struct Pair {
>      int x, y ;
>      ref Pair handle() { return this ; }
> }
> void main () {
>      Pair(1, 2).x = 5 ;
>      Pair(1, 2).handle.x = 5 ;
> }
> --
> nonconst.cpp:
> --
> struct Pair {
>      int x, y ;
>      Pair(int x, int y) : x(x), y(y) {}
>      Pair & handle() { return *this ; }
> } ;
> int main () {
>      Pair(1, 2).x = 5 ;
>      Pair(1, 2).handle().x = 5 ;
> }
>

As a matter of practicality, rvalues are allowed to bind to the 'this' 
parameter of a method. I agree it's a large hole in the current 
philosophy of not letting rvalues bind to references.

Most irritatingly, are things that are typically only values, and don't 
have any references.

For example:

struct S
{
     int v;
     S opBinary(string op)(ref const(S) s2) const if(op == "+")
     {
         return S(v + s2.v);
     }
}

void main()
{
     auto s = S(2);
//  auto s2 = s + S(3); // fails
     auto s2 = S(3) + s; // OK
}

-Steve


More information about the Digitalmars-d-learn mailing list