Counting references of a deleted ReferenceCountedObject

Hi all,

I have a simple struct that extends ReferenceCountedObject:

struct Thing : public ReferenceCountedObject

Which I’m using as follows:

int main (int argc, char** argv)
	ReferenceCountedArray<Thing, CriticalSection> things;
	things.add(new Thing());
	Thing* thing = things[0].get();  // grab a pointer to thing

	std::cout << thing->getReferenceCount() << " refs\n"; 


	std::cout << thing->getReferenceCount() << " refs\n";  // (1)

    return 0;

The docs on ReferenceCountedArray::remove() say:

The object that is removed will have its reference count decreased, and may be deleted if not referenced from elsewhere.

I might be completely wrong here (bear with me), but In my code at (1) the object is no longer referenced from elsewhere. Am I calling getReferenceCount() on an object that has been just removed? How come it doesn’t crash?

It may be random luck. The memory address was not reallocated and the object still “lives” there.
Release or debug mode?

@Matthieu_Brucher I agree with you on the luck part. I’m on Linux, tried both release and debug modes. Same results.

You may see some different results on different platforms.
If you want to check if it’s destroyed, add a destructor with some debug output.

1 Like