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

james.p.leblanc james.p.leblanc at gmail.com
Sun Aug 22 07:58:12 UTC 2021


Hello,

Question about a possible strategy to avoid problems with
undesired/unintended copying of a structure:

1) We have a struct, call this **Foo**.

2) We instantiate it with,   **x = Foo(a,b,c);**
        a.  our constructor will initialize a field:  **this.myadd 
= &this**
        b.  this capture the address of our original "x" in 
x.myadd.

3) We wish to allow, any function calls using x, so we cannot
    disable Foo's this(this).

4) Our goal is to avoid problems with any accidental copying
    of x ... say by doing:  **auto y=x;**

5) the copy of step 4 **does not use the constructor**, thus 
y.myadd
    would contain the address of x (and not y)

6) We can exploit that y.myadd does NOT contain its own
    address (but instead contains the address of x).

    This requires adding logic checks in any Foo opAssign,
    and other overloads.  For example, we can disallow any
    such overloads by checking:

               if( &this != this.myadd ){ ... }

7) Needing to operate on x with other functions implies that
    private or const is not a solution. (I believe.)

Some initial experiments lead me to believe this may acheive
part of what I would like.  But, it feels very "hackish" and
ugly.

Is there a better way?

Best Regards,
James




More information about the Digitalmars-d-learn mailing list