Can't modify this
Maxim Fomin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jul 2 07:32:45 PDT 2014
On Saturday, 28 June 2014 at 20:40:21 UTC, Ary Borenszweig wrote:
> This doesn't work:
>
> class Foo {
> this() {
> this = new Foo;
> }
> }
>
> Error: Cannot modify 'this'
>
> However you can do this:
>
> class Foo {
> this() {
> auto p = &this;
> *p = new Foo();
> }
> }
>
> It even changes the value of this!
>
> Should that compile? I mean, it's the same as modifying
> 'this'...
D language was not aimed toward preventing any attepmt to
circumvent some hypothetical limitations (it does not even cope
with things which it should definetely prevent). There are holes
much - much worse. And changing value of this parameter is not a
problem anyway, since it is possible to have typeid(this) !=
typeid of type of current method which is bigger problem than
pointing to different value of same type.
More information about the Digitalmars-d-learn
mailing list