Best way to reference an array in a child class...

Steven Schveighoffer schveiguy at yahoo.com
Fri Mar 7 05:57:31 PST 2014


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


More information about the Digitalmars-d-learn mailing list