Hi!
I recently ran into a crash, where I had declared member objects of a class in the wrong order. Basically, member A was using member B, but member B was declared after member A. So, when member A was trying to use member B, that did not work, cause member B was not yet constructed.
My question is: how can I prevent this? My compiler did not flag this. Neither XCode nor Visual Studio warned me.
Is it possible to make the compiler aware of this? Or is it possible to use a certain code pattern, so that this problem cannot happen?
Its probably best, if I post example code, so you understand my case better:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
class Foo
{
public:
Foo()
{
data = new int();
}
~Foo()
{
delete data;
}
void setData(int newValue)
{
*data = newValue;
}
private:
//a pointer to an int:
int* data = nullptr;
};
class Bar
{
public:
Bar(Foo& foo)
{
foo.setData(42);
}
};
class CrashTest
{
public:
CrashTest() : bar(foo)
{
}
private:
Bar bar;
Foo foo;
};
main()
{
CrashTest crashTest;
}
|
So here, the class CrashTest is declaring two class members: bar and foo. bar is declared first. BUT: bar is using foo. Cause in the constructor of bar, it requires a Foo object. Now, when bar tries to access foo, the constructor of foo has not yet run. That means, it has not initialised its data. And thus the access from bar to foo is invalid. And it crashes.
One solution is, to reverse the order of declaration in CrashTest. If I declare foo first, and bar seconds, things are fine.
So this is obviously a bug of mine! But I would like a way to prevent this in the future.
Can I somehow make the compiler aware of this so that it generates a warning? Cause currently it does not warn about it.
Or can I use some kind of code pattern, which prevents me from making this mistake ever again? :-)
Curious to see what people here think :-)