Copying structs via function (not bitwise)
Matthias Walter
walter at mail.math.uni-magdeburg.de
Thu Feb 14 06:03:02 PST 2008
Bill Baxter Wrote:
> Matthias Walter wrote:
> > Bill Baxter Wrote:
> >
> >> Matthias Walter wrote:
> >>> Is there any other way of copying structs with '=' operator, other than the default way of a bitwise copy? I quote the FAQ:
> >>>
> >>> "Structs, being value objects, do get copied about. A copy is defined in D to be a bit copy. I've never been comfortable with any object in C++ that does something other than a bit copy when copied. Most of this other behavior stems from that old problem of trying to manage memory. Absent that, there doesn't seem to be a compelling rationale for having anything other than a bit copy."
> >>>
> >>> The reason, I'm asking for this, is that I'm working on a GMP port. Because numbers _must_ be value types, I must use structs. But as different instances of the same number must reference another memory region of the GMP internals, I must call special copy functions, if I do "a = b;" on two gmp-structs, a refers to the same gmp-internal memory as b.
> >>>
> >>> Is there any way to do this?
> >>>
> >>> best regards
> >>> Matthias Walter
> >> opAssign can be used to override the meaning of A=B where A and B are
> >> different types. But by design you can't change the meaning A=B where A
> >> and B are the same type.
> >>
> >> But you could make it work using any of the following:
> >>
> >> A ~= B;
> >> A.foo = B;
> >> A = B.foo;
> >> assign(A,B);
> >> A.assign(B);
> >> etc..
> >>
> >> And I'm sure downs could suggest a few more workable syntaxes. :-)
> >>
> >> --bb
> >
> > Problem is that GMP-structs should behave like normal numbers and one also does not write:
> > int i;
> > i.value = 10;
> >
> > Does this mean, that in the current situation, it is impossible to port the GMP library with structs so that
> >
> > T i,j = 0;
> > i = j;
> > j++;
> > assert (i == 0);
> >
> > works for T = int, T = long, T = float, T = gmp_struct ?
> >
> > best regards
> > Matthias Walter
>
> Yep. That's what it means. I don't know what's in gmp_struct but if it
> includes a pointer to something that must be allocated then D ain't
> gonna be able to do it.
>
> But D2 is supposedly going to be getting features to make ref-counting
> smart pointer structs possible, and I'm pretty sure that means there has
> to be some way to trigger side effects upon assignments.
>
> --bb
Okay, then I know on it for now. The problem is indeed, that the C-library for GMP must allocate some memory for the number, meaning you always only maintain some pointers to that memory. bitwise-copy would then lead to a double reference to the same number...
best regards
Matthias Walter
More information about the Digitalmars-d-learn
mailing list