Pebbles, Sand and Milk

5 08 2010

Well, there’s this old story about a glass, some pebbles, sand and milk [or beer for those of you that still drink the stuff]. I’m not going to repeat it, look it up it’s an amusing little bit. Bottom line says that the order of actions matter as much as the actions themselves; a good lesson all around and never more fitting for me than yesterday.

I’ve gone back to change a little functionality in one of my matrix classes. It wasn’t anything groundbreaking and I figured, go in, take 20 minutes [expected it to take 10 really] and get back to my other project. Ha, I should’ve known better than that. It’s the little things that matter.

The code that gave me trouble was this:
struct Matrix2Fixture
{
  Matrix2 matrix;
  Matrix2::value_type m0;
  Matrix2::value_type m1;
  Matrix2::value_type m2;
  Matrix2::value_type m3;
  ~Matrix2Fixture(){}
  Matrix2Fixture()
  : m0(0)
  , m1(1)
  , m2(2)
  , m3(3)
  , matrix(m0,m1,m2,m3)
{}
};

Compile, run and go. In theory.
Compile run and watch ALL of my tests fail was the harder reality… But, why?

A few breakpoints, a few couts, I even checked the order of construction of the matrix hierarchy [it’s a little hierarchy to specialize the top most data struct, nothing major and no virtual functions in sight]. Everything seemed to be in order, yet the Matrix2 constructor kept getting garbage. I was a bit frustrated, went out for coffee.

An hour later [of a 10 minute job] and something tickled the dark regions of my brain. Hmm…
The order of construction of static objects across multiple compilation units is undefined; I know it, you know it, every C++ programmer knows it. But what about the order of initialization of member variables within the object constructor?

And it hit me, like a truck, it’s not about the initialization list, it’s about the declaration order.
struct Matrix2Fixture
{
  Matrix2::value_type m0;
  Matrix2::value_type m1;
  Matrix2::value_type m2;
  Matrix2::value_type m3;
  Matrix2 matrix;
  ~Matrix2Fixture(){}
  Matrix2Fixture()
  : m0(0)
  , m1(1)
  , m2(2)
  , m3(3)
  , matrix(m0,m1,m2,m3)
{}
};

Spot the differences. That works, all is good and I’ve learnt not to try to drink my milk before I put sand and pebbles in… Or coffee, whatever tickles your fancy.

“The sun is the same in a relative way but we’re older, shorter of breath and one day closer to death”

Advertisements

Actions

Information

Leave a Reply

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




%d bloggers like this: