Object arrays in D
simendsjo
simendsjo at gmail.com
Tue Apr 10 05:07:58 PDT 2012
On Tue, 10 Apr 2012 13:58:44 +0200, CrudOMatic <crudomatic at gmail.com>
wrote:
> Sorry, but a small issue.
>
> the line: auto card = cards.popBack();
>
> throws the errors:
>
> error: variable xxx.card voids have no value
> error: expression popBack(this.cards) is void and has no value
>
> I tried reserving the space, I even tried cards = new Card[no_cards];
Sorry, popBack returns void. You have to get the back of the array before
calling popBack(). Here's an example:
import std.array;
class Card {}
void main() {
Card[] cards;
cards.reserve(1024);
assert(cards.capacity >= 1024);
assert(cards.length == 0); // still 0
cards ~= new Card(); // add a Card
assert(cards.length == 1);
auto card = cards.back; // get last element
cards.popBack(); // remove last element
assert(card); // non-null
assert(cards.length == 0); // "empty" again
assumeSafeAppend(cards); // allow us to append to it without
reallocating
auto oldptr = cards.ptr;
cards ~= new Card();
assert(cards.length == 1);
assert(card); // card still alive and kicking
assert(cards.ptr == oldptr); // and no reallocation
}
More information about the Digitalmars-d
mailing list