Why can't we make reference variables?

Era Scarecrow rtcvb32 at yahoo.com
Wed Aug 29 14:37:32 PDT 2012


On Wednesday, 29 August 2012 at 19:55:08 UTC, Tommi wrote:
> I honestly don't know anything about memory safety and what it 
> entails. So, I can't comment about any of that stuff. But if 
> you say general ref variables can't be implemented in @safe 
> mode, then I can just take your word for it. But what I'm 
> saying is that ref variables would be a nice feature to have in 
> @system code.

  They can be used safely if they are heap allocated (or global).

> My logic is very simple: since we can use pointers in @system 
> code, and references are no more unsafe than pointers, then we 
> should be able to use references in @system code. You might 
> argue that references are little more than syntactic sugar (and 
> a bit safer) compared to pointers, but you shouldn't 
> underestimate the importance of syntactic sugar especially when 
> you're trying to lure in users of C++.

  Maybe. But the scope of referencing variables should likely be 
left alone. I am not sure of all the details of C++ references 
either. Ref hides the fact it's a pointer/reference. This means 
unless you really know what you're doing that it is not a good 
thing to use.

  Let's assume we compare a pointer and a ref in a struct and 
copying.

  struct P {
    int* ptr;
  }

  struct R {
    ref int r;
    this(ref int i) {r = i;}
  }

  int value;
  P p1, p2;

  p1.ptr = value; //Compile error, not a pointer, need to use 
&value
  p2 = p1;
  p2.ptr = 100; //compile error, need to use *p2.ptr = 100

  value = 42;
  R r1 = R(value)
  R r2 = r1;      //both reference value now
  r2.r = 100;     //r must be a variable if this succeeds

  assert(r1.r == 42, "FAIL!");
  assert(r2.r == 100, "Would succeed if it got this far");


  If I have this right, as a pointer you know it's a 
pointer/reference and don't make more obvious mistakes as you're 
told by the compiler what's wrong. Also since it hides the fact 
it's actually a pointer hidden bugs are bound to crop up more 
often where reference variables were used.

  If we return now r1 or r2, it silently fails since it can't 
guarantee that the reference wasn't a local stack variable, or of 
anything at all really. As a pointer you can blame the programmer 
(It's their fault afterall), as a reference you blame the 
language designer.

  What would you do for the postblitz if you can't reset the 
reference? Or if you could, would you do...? It would be so easy 
to forget.

  this(this) {
    r = new int(r);
  }


  *Prepares for flames from Walter and Andrei*


More information about the Digitalmars-d mailing list