Archived

This topic is now archived and is closed to further replies.

thedo

Why AddRef()?

Recommended Posts

thedo    124
I posted a question on a forum a while ago and one person said I shouldn''t forget to use AddRef() (the code passed a LPDIRECT3DDEVICE8 to my mesh class). Why should I do this? I have never done it before and my code has always *seemed* to run fine. If LPDIRECT3DDEVICE8 is only a pointer to an IDirect3DDevice8 anyway, I''m not duplicating the Device, just copying a pointer to it. According to the docs I would also need to call the Release() for every AddRef() I call. If I forget this then surely I might end up with memeory leaks. I just don''t know why this needs to be done. Input please. Neil (Sorry if that seemed like ranting - it wasn''t meant to - I just feel like i''m missing out on something really simple) WHATCHA GONNA DO WHEN THE LARGEST ARMS IN THE WORLD RUN WILD ON YOU?!?!

Share this post


Link to post
Share on other sites
CrazedGenius    156
AddRef increases the reference count
Release decreases the reference count and destroys the object when the reference count becomes zero

AddRef essentially tells an object that you have a hold of it and that it shouldn''t be destroyed until you and all the other "holders" have let go (called Release). Therefore, you should call AddRef if you fear that there''s a chance that the object may be destroyed before you are done with it.

If, for some reason, you believe that this will not be an issue - that is, you know that all objects that use a Object X will be destroyed before Object X is destroyed, then you probably don''t need to call ObjectX->AddRef().

Either way, that''s the idea behind AddRef()

Share this post


Link to post
Share on other sites
Promit    13246
Short answer: COM specs.

The helpful answer: As part of the COM specification, each object manages it''s own memory destruction. As a result, it needs to know when it is actually supposed to destroy itself. WHat it does is it maintains a _reference count_. This is a count of how many pointers currently have access to that object.(Always pointers; IDirect3D* will work, IDirect3D will not) The AddRef function is part of the IUnknown interface, which has three methods(i wont actually provide the params): QueryInterface(...), AddRef(), and Release(). AddRef increases the reference count. YOu do this when you copy a pointer. Release decreases the reference count. You usually get:
COMObject->Release();
COMObject = NULL;
This is opposed to standard C++ destruction:
delete COMObject; //Do NOT do this with COM objects
COMObject = NULL;

So, yeah, just call AddRef when you copy a pointer, and Release when you are done.

-----------------------------
The sad thing about artificial intelligence is that it lacks artifice and therefore intelligence.

Share this post


Link to post
Share on other sites