I caught an interesting bug. I have a shared pointer that I forgot to return from a function, and it appears the destructor was called for the object, and I believe the memory on which the destructor was called was junk:
struct MySharedPointer
{
MySharedPointer() : ptr(nullptr) {}
int ref_count = 0;
char* ptr;
void reset()
{
if (!ptr) return;
// CHECK IF REFERENCE COUNT IS HIGHER THAN ZERO.
// THIS POINTER IS STILL HOLDING IT SO IT MUST BE GREATER THAN ZERO
// BUT IT ISN'T, I BELIEVE IT HAS JUNK VALUE
delete ptr;
}
~MySharedPointer()
{
reset();
}
};
MySharedPointer myfunc()
{
std::cout << "Hello";
// I didn't return here
}
int main()
{
myfunc();
}
I know this is plainly an error, but I would like to understand what is happening. Is it the case that it's what I suspect, that because I didn't return a value the destructor is simply being called on blank/junk/uninitialised memory? In the example I gave the compiler caught that I wasn't returning a value, but in my program it didn't catch it.