I don't get it. version(unittest) can't seem to use local variable
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jul 12 21:30:44 PDT 2014
On Sat, Jul 12, 2014 at 09:20:06PM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
> On 07/12/2014 08:37 PM, H. S. Teoh via Digitalmars-d-learn wrote:
>
> > ref makes it possible for the caller to modify the pointer returned by
> > the callee. For example:
> >
> > class D { int x; }
> > class C {
> > D d;
> > this(D _d) { d = _d; }
> > ref D getPtr() { return d; }
> > }
> > auto d1 = new D;
> > auto d2 = new D;
> > auto c = new C(d1); // c.d now points to d1
> > assert(c.getPtr() is d1); // getPtr returns d1
> > c.getPtr() = d2; // this modifies c.d
> > assert(c.getPtr() is d2); // getPtr now returns d2
> >
> > If you do not wish the caller to do this, remove the ref from the
> > function signature.
>
> The twist here is that the OP's function returned 'this' by reference.
> Changing that not only not have any effect on the object, it would
> also be undefined behavior because 'this' is a local variable in that
> use.
>
> class C {
> ref C getPtr() { return this; }
> }
>
> void main()
> {
> auto c = new C();
> assert(c.getPtr() is c);
>
> c.getPtr() = new C(); // modifying dead variable
> assert(c.getPtr() is c); // no effect
> }
[...]
Hmm. Shouldn't this be a compiler bug?? Returning a ref to a local
variable should be illegal, even implicit ones like 'this'.
T
--
If you want to solve a problem, you need to address its root cause, not just its symptoms. Otherwise it's like treating cancer with Tylenol...
More information about the Digitalmars-d-learn
mailing list