I ran into this bizarre pointer-less situation in my code and am now wondering if there is a way to detect it (other than crashing). The code manages to get into an un-constructed object’s method. When b1 is constructed, a has not been constructed, and b tries to use it. By the time b2 is constructed, a is properly constructed and the code works as expected.
Beyond the obvious, “don’t do this in your code,” I’m wondering if there’s a way to detect this at compile or run time. The compiler didn’t detect it at all, and I just got some obscure and very unhelpful message about running managed code while initializing a DLL when the program crashed.
I tried to test “this”, but it’s not NULL because memory has been asigned — it’s just that the constructor has not been called so the memory is in an indeterminate state.
I would have thought the compiler would stick in some debug code to detect when this happens, but I guess not.
Is there any assertion or test or compile time switch I can use to detect this situation, or does it just come down to, “if it hurts, don’t do that?”
OUTPUT:
(NULL)
test
#include "stdafx.h"
#include "cstring"
class Apple
{
char *sometimesinitialized;
public:
Apple () {
sometimesinitialized = new char[15];
strcpy_s(sometimesinitialized, 5, "test");
};
void test()
{
printf("%s\n", sometimesinitialized);
}
};
class Ball
{
public:
Ball();
};
Ball b1; // OOPS!
Apple a;
Ball b2; // Works as expected
Ball::Ball()
{
a.test();
}
int _tmain(int argc, _TCHAR* argv[])
{
scanf_s("%i");
return 0;
}
If an instance of
Bneeds to access an instance ofAthen it should be passed toB‘s constructor.