C++ Class: AutoUnRef

Not sure if this is the correct forum.

Essentially I got lazy when I had to unreference an object.

So I came up with this class.

This allows you to:



AutoUnRef tbl = Lua()->GetNewTable();


And forget about unreferencing it.

AutoUnRef works just like any other ILuaObject *, so it works anywhere.

Except when the C++ method returns, it will delete the AutoUnRef object causing the destructor to be called and then unreferencing the lua object.


class AutoUnRef
{
public:
	AutoUnRef(ILuaObject *obj)
	{
		m_obj = obj;
	};

	~AutoUnRef()
	{
		if(!m_obj)
			return;

		m_obj->UnReference();
	};

	ILuaObject* operator -> () const
	{
		return m_obj;
	};

	operator ILuaObject*()
	{
		return m_obj;
	};

	operator ILuaObject*() const
	{
		return m_obj;
	};

	const AutoUnRef& operator=(const ILuaObject *obj)
	{
		m_obj = (ILuaObject *)obj;
	}

private:
	ILuaObject *m_obj;
};

I hope this comes in handy to someone.

Aren’t lua objects in a table automatically un-referenced and removed if you set the table’s __mode to “v”?

That’s a completely different kind of “reference”.

Alright.