Reference counter question

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Post Reply
Methuselah
Posts: 19
Joined: Fri Nov 24, 2006 9:33 am

Reference counter question

Post by Methuselah »

I was poking around the source and noticed something about the reference counter. The line that actually destroys the object in the drop function is in IReferenceCounter, which most classes inherit from. But does "delete this;" in the context of an IReferenceCounter object delete any memory belonging to subclasses? My first thought was that it wouldn't, since it simply does not know what those classes contain - so it's essentially just calling the IReferenceCounter destructor. I cooked up a simple example to test it out:

Code: Select all

#include <iostream>
using namespace std;
class ref
{
public:
	int refCount;

	ref() : refCount(1)
	{}
	
	void release()
	{
		if (--refCount == 0)
			delete this;
	}

	~ref()
	{
		cout << "ref destructor" << endl;
	}
};

class foo : public virtual ref
{
public:
	~foo()
	{
		cout << "foo destructor" << endl;
	}
};

int main()
{
	foo* example = new foo();
	example->release();
}
tldr; - ref is a dumb reference counter that calls delete this when it reaches 0 and foo inherits from it.

On MSVS2010 this piece of code crashes after printing out "ref destructor" with an invalid block type (debug assertion). It's the same thing as if you tried to call delete on a pointer to an object that was already deleted. It seems to me like the destructors are getting called in the reverse order.
So I guess my question is what's happening with Irrlicht's reference counters, because the code would point towards a crash (by my logic), but as we all very well know, Irrlicht does not go around crashing every time it reaches a ref count of 0 on some object? Could someone find what's wrong with this brainfart or point me towards some code that's taking care of this?
Xaryl
Posts: 90
Joined: Sat Apr 30, 2011 11:54 pm

Post by Xaryl »

The destructor for the base class needs to be virtual.
Methuselah
Posts: 19
Joined: Fri Nov 24, 2006 9:33 am

Post by Methuselah »

Thanks, I hadn't noticed that both destructors were virtual. I guess it makes sense though.
Anyway, admins - feel free to send my brainfart topic to the nether.
CuteAlien
Admin
Posts: 9721
Joined: Mon Mar 06, 2006 2:25 pm
Location: Tübingen, Germany
Contact:

Post by CuteAlien »

Why remove? It was a good question, came with code-example and has a good answer. I wish more topics were like this one :-)
IRC: #irrlicht on irc.libera.chat
Code snippet repository: https://github.com/mzeilfelder/irr-playground-micha
Free racer made with Irrlicht: http://www.irrgheist.com/hcraftsource.htm
Post Reply