Vector initialization: Cross-platform gotcha

Well, oops; my fix for the map-crash bug broke the PC build. After a lot of head-scratching and some help from Ramp, he finally tracked it down to a crash in my new code, specifically in the RemoveSuperCells part of the destructor.

if ( _cells.empty() == false )

Somehow on the PC “empty()” was returning true while the vector was full of garbage. This rang a bell, the constructor for the Supercell is this:

SuperCell(Renderer* r, …)
    : _renderer(r)
// …
    , _cells(64) // — gotcha
{
}

Under GNU, this initializes the vector with an initial capacity of 64, equivalent to calling vector.reserve(64). Microsoft’s 2008 STL, however, changes the size of the vector like caling vector.resize(64) which creates a vector of 64 garbage entries.

The solution is simply to call reserve manually:

if ( _cells.empty() == false )[/sourecode]

Somehow on the PC “empty()” was returning true while the vector was full of garbage. This rang a bell, the constructor for the Supercell is this:

SuperCell(Renderer* r, …)
    : _renderer(r)
// …
    , _cells() // — construct it anyway
{
    // We’re always going to want a dozen or so
    // cells at least, so lets get all that reallocing
    // out of the way now…
    _cells.reserve(64) ; // — populate now
}

The optimizer in me is disappointed at this because passing the initial size in the constructor means that the memory is only allocated once. Doing it this way creates an initial allocation and then reallocs it, it might only be a few CPU instructions but it’s still a few CPU instructions.

7 Comments

All these subtle differences between the two compilers sounds like a nightmare.

Isn’t this why you should use one implementation of the STL for all platforms rather than the default implementation for each compiler when building cross platform?

Oli, can you fire up the Ventrillo?

Of course I can :) But I’m exhausted so I can’t be bothered to :)

C++ and STL give you high velocity 37mm shells to shoot off your foot with…

Only if the feet have been modeled ;)

Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

You may use these HTML tags and attributes:

<a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: