Jump to content
  • Advertisement
Sign in to follow this  
Flug540

Object life cycle

This topic is 2095 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!