July 13, 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...
July 13, 2014
On Sat, Jul 12, 2014 at 09:30:44PM -0700, H. S. Teoh via Digitalmars-d-learn wrote:
> On Sat, Jul 12, 2014 at 09:20:06PM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
[...]
> > 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'.
[...]

Filed as bug:

	https://issues.dlang.org/show_bug.cgi?id=13116

It's pretty serious, since it causes memory corruption. In fact, it also breaks @safe-ty (see second bug note in above link).


T

-- 
The early bird gets the worm. Moral: ewww...
1 2
Next ›   Last »