Moving structs containing strings ...
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Mon Apr 24 08:25:13 PDT 2006
Bob W wrote:
> "Derek Parnell" <derek at psych.ward> wrote in message
> news:c7u4nwvom7ca$.o0vru71wqxwe.dlg at 40tude.net...
>> Another solution is to recalculate the addresses of the id strings after
>> changing the length ...
>>
>> arr=arr[0..2]; // adjust length
>> foreach( inout Sc s; arr)
>> s.id = s.idz[0..s.id.length];
>>
>
> I'll gladly accept this as a solution, because it will
> utilize existing strings within the structs-array.
>
> The workaround you have posted earlier allocates
> memory and duplicates strings one by one. That is
> something I would not want to try in real-world
> applications due to obvious reasons.
How about defining the struct like this:
struct Sc { uint val; char[3] idz; char[] id() { return idz[0..3]; } }
This turns 'id' into a property instead of a field. This might be
slightly slower*, but has several advantages:
- It will always return the current string without needing manual updates.
- It doesn't allocate.
- It removes the need to initialize 'id' separately.
- Added bonus: Sc.sizeof is halved. (goes from 16 bytes to 8 bytes)
*) Not necessarily though, it may well be optimized out.
More information about the Digitalmars-d-bugs
mailing list