Copying structs via function (not bitwise)

Bill Baxter dnewsgroup at billbaxter.com
Thu Feb 14 04:09:21 PST 2008


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


More information about the Digitalmars-d-learn mailing list