June 03, 2013 Re: Structs should not contain pointers to internal data | ||||
---|---|---|---|---|
| ||||
On Monday, June 03, 2013 10:23:43 Saurabh Das wrote: > Hello Learn-D, > > I'm new to D from a C/C++ background. One caveat of defining structs in D that I came across was that structs should be bit-wise relocatable and hence should not contain pointers to internal data members. > > So that essentially means that code of the form (below) is disallowed. > > struct S1 > { > int x; > int* p = &x; > } > > What I'm wondering is, are references also disallowed? As in: > > struct S2 > { > int x; > ref int p = x; > } > > I ask this because in C++, I have a telemetry class which publishes the value of any member variable over TCP. I was trying to achieve similar functionality in D and am wondering how to go about designing it. It's not legal to use ref on local variables, just function parameters, so it's not even a question of whether a struct can have a ref to itself. It can't have a ref in the first place. > Ideally I'd like to have: > > struct Telemetry(T) ... > > struct UsefulStruct > { > int importantValue; > auto tel1 = Telemetry!int(importantValue); > } > > Essentially I'm asking whether the above is a valid construct in D. Well, you could pass importantValue by ref to Telemetry's constructor, but since it's impossible for it to keep a ref to it, you're not going to run into problems with UsefulStruct having a reference to itself or Telemetry having a reference to anything in UsefulStruct. You're only option is pointers, and you can't do anything that won't work if a struct is moved with a bitwise copy, or you'll have nasty bugs. - Jonathan M Davis |
Copyright © 1999-2021 by the D Language Foundation