Potential strategy for avoiding problems with copy of a struct (maybe??)

james.p.leblanc james.p.leblanc at gmail.com
Sun Aug 22 13:03:20 UTC 2021


On Sunday, 22 August 2021 at 11:10:33 UTC, jfondren wrote:
> On Sunday, 22 August 2021 at 07:58:12 UTC, james.p.leblanc 
> wrote:
>> Hello,
>>
> If you don't get an answer that you like, I suggesting posting 
> functional code and then stating your dissastisfactions with it.

Mattias, jfondren,

Thanks both for your replies, I always learn something from them.

I've trimmed my code to a minimal example to give a better idea
of my thinking on this.  You will notice that  to ensure that I
"seed" x with its real address at initialization, I must add 
@disable
this() to my struct.

import std.stdio;

     struct Foo {
         int a, b, c;
         Foo* myadd;

         this(int a, int b, int c) {
             this.a = a;
             this.b = b;
             this.c = c;
             this.myadd = &this;
         }

         @ disable this();
     }

     void main() {

         // x is original, we wish to protect
         auto x = Foo(1, 2, 3);

         // y is the "bad copy", do not want operation on y to 
pollute original x
         auto y=x;

         writeln("&x: ",&x,", x.myadd: ",x.myadd,", the 2 agree, 
we have original!");
         writeln("&y: ",&y,", y.myadd: ",y.myadd,", these 2 
disagree (must be a bad copy!");

}

Produces output:

&x: **7FFC65C02CC8**, x.myadd: **7FFC65C02CC8**, the 2 agree, we 
have original!
&y: 7FFC65C02CE8, y.myadd: **7FFC65C02CC8**, these 2 disagree 
(must be a bad copy!

So, as stated, in my struct overloading I can check if my two 
values agree
or not (exposing whether or not I have the original, or a copy), 
and react
appropriately.

I understand that the language allows circumvention of this 
method... but
I just want to catch minor mistakes in programming.

Again, all comments and thoughts are welcome.

Best Regards,
James




More information about the Digitalmars-d-learn mailing list