Me vs. The Compiler
Mar. 30th, 2017 11:49 pmI figured out the source of yesterday's problem.
I had put in a forward definition for a class in a header file so that I could declare a pointer to an object of that type inside the class that was defined in the header file. Like this:
When I destroy ThisClass, I want to destroy the instance of AnotherClass that it contains. No problem. I'll just call delete on the pointer like this:
That should work just fine.
Except it didn't. Because I hadn't actually included the header file for AnotherClass in the .cpp file for ThisClass. What I would have expected was that this should have produced a compile error telling me that I was operating on a class that hadn't been completely defined.
But there was no compile error. Instead, the Visual Studio compiler just called delete on anotherClassInstance like it was a pointer to a random chunk of memory with no destructor.
Hilarity ensued.
Well, at least I should remember what caused me to waste so much time the next time I run into this problem...
*grumble*
I had put in a forward definition for a class in a header file so that I could declare a pointer to an object of that type inside the class that was defined in the header file. Like this:
class AnotherClass; class ThisClass { ... AnotherClass* anotherClassInstance; };
When I destroy ThisClass, I want to destroy the instance of AnotherClass that it contains. No problem. I'll just call delete on the pointer like this:
delete anotherClassInstance;
That should work just fine.
Except it didn't. Because I hadn't actually included the header file for AnotherClass in the .cpp file for ThisClass. What I would have expected was that this should have produced a compile error telling me that I was operating on a class that hadn't been completely defined.
But there was no compile error. Instead, the Visual Studio compiler just called delete on anotherClassInstance like it was a pointer to a random chunk of memory with no destructor.
Hilarity ensued.
Well, at least I should remember what caused me to waste so much time the next time I run into this problem...
*grumble*