Sign in to follow this  
Xsy

COM Objects - Reference Addition

Recommended Posts

Xsy    140
Hey. I've stumbled upon something and im curious of the cause. I'm using D3D11 and sometimes I need to pass the device around. Basically what i'm doing is to create an ID3D11Device via the CreateDevice function. On creation a pointer to the device object is created , according to my belief this is the first reference. After-wards I pass the device object by reference to a function like this: (Not realy like this , but the operation is the same )

class SomeClass
{
 ~SomeClass()
  { 
   p_Dev->Release();
  }

  void Foo( ID3D11Device& device )
  {
  p_Dev = &device
  }

 ID3D11Device * p_Dev;
}



Now my initial thought is that the operation of Foo invokes a call to AddRef and adds another reference , because there is another pointer pointing to the device object. The problem occurs upon release , if I release both the the first and second pointers , I get an error when I try to release one after the other. On the other hand when I release only one of them , the D3D11 debug returns that everything is cleared successfully. Why is that ? :)

Share this post


Link to post
Share on other sites
Sneftel    1788
Quote:
Original post by Xsy
Now my initial thought is that the operation of Foo invokes a call to AddRef and adds another reference , because there is another pointer pointing to the device object.
If nothing calls AddRef, then AddRef is never called. C++ doesn't keep track of references for COM automatically. Instead, AddRef must be explicitly called to increment the reference count, and Release must be explicitly called to decrement the reference count. If you want these operations to be handled for you, look into CComPtr, or how to use shared_ptr for COM references.

Share this post


Link to post
Share on other sites
Xsy    140
I just assumed that , because when I pass a COM Object pointer to a function using pass by pointer the reference count is incremented automatically without calling AddRef explicitly , so I logically thought that when I pass by pointer a , new pointer copy is created and the ref count increases , therefor if I use an assignment operator between two COM Object pointers the same happens. Guess I was wrong :> Thank's for clarifying that to me!

Share this post


Link to post
Share on other sites
Sneftel    1788
Quote:
Original post by Xsy
when I pass a COM Object pointer to a function using pass by pointer the reference count is incremented automatically without calling AddRef explicitly
No it isn't.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this