🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Object life cycle

Started by
1 comment, last by WitchLord 10 years, 5 months ago
Just started learning AngelScript and not quite clear on how the reference counting works in AngelScript. Let's say we have a class defined in C++:

class MyClass
{
public:
MyClass()
: m_RefCount(1)
{
// Init stuff.
}

~MyClass()
{
// Free stuff.
}

static *MyClass Factory();
void AddRef();
void Release();

protected:
int m_RefCount;
};

Then we register it with AngelScript:

Engine->RegisterObjectType("MyClass", 0, asOBJ_REF);
Engine->RegisterObjectBehaviour("MyClass", asBEHAVE_FACTORY, "MyClass@ f()", asFUNCTION(Name::Factory), asCALL_CDECL);
Engine->RegisterObjectBehaviour("MyClass", asBEHAVE_ADDREF, "void f()", asMETHOD(MyClass, AddRef), asCALL_THISCALL);
Engine->RegisterObjectBehaviour("MyClass", asBEHAVE_RELEASE, "void f()", asMETHOD(MyClass, Release), asCALL_THISCALL);

Now I'm able to use the class in a script:

void main()
{
MyClass obj;

// Do something with the object.
}

After the object is created, the reference count is set to 1 by the constructor and remains unchanged. What I expected to happen is when 'main' finishes and 'obj' goes out of scope, the object should be destroyed, but it's not, the destructor is never called. Am I supposed to register the destructor? Or is it by design and the object has to be registered as asOBJ_VALUE for the destructor to be called automatically (I'd prefer to leave it as asOBJ_REF)? What is the best way to handle the destruction in this case?

Thanks!
Advertisement
Never mind, was probably some stuck binary from previous build. Rebuilt the project and now the destructor gets called. Still would like to get a confirmation that the object management I described is "proper" in AngelScript context.
Your understanding is correct.

Objects registered as reference types should delete themselves in the Release() method when the refcount reaches 0.

Remember that reference objects may outlive the scope in which they were declared if a handle to it is stored elsewhere (i.e refcount > 0).

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

This topic is closed to new replies.

Advertisement