Best way to reference an array in a child class...
captain_fid
bell.hue at gmail.com
Fri Mar 7 13:45:25 PST 2014
On Friday, 7 March 2014 at 13:57:31 UTC, Steven Schveighoffer
wrote:
> On Thu, 06 Mar 2014 17:44:09 -0500, captain_fid
> <bell.hue at gmail.com> wrote:
>
>>
>>>> this() {items = [ {10, "first"}, {20, "second"}];}
>>
>> strangely enough, when modeling this the first time (using
>> items as a class) and 'new item() syntax) there was no real
>> issue.
>>
>> I thought using a static array of structs in the children
>> would be more efficient when instantiating the objects. Never
>> mind whether its true or not - Speed isn't a really a concern,
>> learning is.
>
> I missed this the first time. That is a difference between my
> code and your code. Mine creates a new instance of an array on
> *object* initialization, yours creates ONE instance of an
> array, that all objects share.
>
> This is not necessarily a good thing. Because you've created a
> mutable version of the array. I believe it is initialized on
> startup from the heap.
>
> One really bad thing is, the same array is used if you
> initialize from multiple threads. And it's mutable, making it
> implicitly shared even though it shouldn't be. You should make
> the array immutable and static, or else initialize it in the
> constructor. I don't know your use case, so it's hard to say
> what you should do.
>
> -Steve
>> I don't know your use case, so it's hard to say what you
>> should do.
Steve, I don't think I know my use case -- So it's not you. I'm
attempting to model hardware, where 'items' in this case are an
static array of registers. Single threaded (for now). Mainly,
this a learning opportunity to get a better understanding of D
for future comparison (vs. C++).
> This is not necessarily a good thing. Because you've created a
> mutable version of the array. I believe it is initialized on
> startup from the heap.
Lot to learn. I understand initialized from the heap, but do you
mean at program startup, or object instantiation? If program, I
would have expected that with __gshared (globals) only, not with
this.
> One really bad thing is, the same array is used if you
> initialize from multiple threads. And it's mutable, making it
> implicitly shared even though it shouldn't be. You should make
> the array immutable and static, or else initialize it in the
> constructor.
I appreciate your suggestions and the patience.
More information about the Digitalmars-d-learn
mailing list