Object arrays in D

Steven Schveighoffer schveiguy at yahoo.com
Tue Apr 10 04:35:31 PDT 2012


On Tue, 10 Apr 2012 03:41:28 -0400, CrudOMatic <crudomatic at gmail.com>  
wrote:

> The D documentation is a little lacking in a lot of areas. I'm needing  
> to know an exact way of making arrays of objects.
>
> For example:
>
> /* Deck class */
> 	// Will be adjusted with the proper cards for each game type
> 	class Deck {
> 		/* Card count - used to keep track of how many cards are left in the  
> deck - when zero, Deck is discarded from the Shoe */
> 		int cardCount;
> 		/* Cards array - initialized to cardCount elements */
> 		Card cards[];
> 		
> 		/* Constructor */
> 		this(int no_cards) {
> 			cardCount = no_cards;
> 			cards = new Card[cardCount];
> 		}
> 		
> 		/* Destructor */
> 		~this() {
> 			delete cards;
> 		}
> 	}

I want to stop you right there.  *DON'T* use a destructor here, you will  
have issues, mostly of the random segfault nature.

Quickly explained, if the Deck class and it's cards array are destroyed at  
the same time in the GC, there is no guarantee that the cards array is  
valid when you try to destroy it.

Destructors are strictly for cleaning up resources that *AREN'T* allocated  
by the GC.  For example anything created with C's malloc, or an open file  
descriptor, etc.

> the cards[] array is meant to be an array of Card objects, and I'm  
> initializing it in the constructor as seen above. This hasn't been  
> tested yet, but I'm needing to know if this is the correct way of doing  
> it - to save headaches later.

This is fine.  Note that D slices (what cards[] is) contain a length  
member, so no need to store an extra member.

> Also, while I'm here, how would you go about moving objects from the  
> cards array in the Deck class to another class containing a cards array  
> - I'm talking about MOVING them, not COPYING them. I don't want any  
> issues with references being destroyed after being moved to another  
> class when I happen to destroy an instance of the Deck class.

All classes are references (i.e. an element of cards is a single pointer  
to a Card instance). There is no need to move them, as a straight copy is  
just copying the reference.  And since you have removed the dtor, there  
should be no worry about accidentally destroying the cards ;)

You really should read the spec page on classes  
(http://dlang.org/class.html) and I highly recommend picking up the D  
programming language book.

-Steve


More information about the Digitalmars-d mailing list