tags:

views:

685

answers:

2

Does CoCreateInstance automatically calls AddRef on the interface I'm creating or should I call it manually afterwards?

+6  A: 

In short: No.

You don't need to call AddRef in your code.

A reference counter which COM object has is 1 after CoCreateInstance.

So, if you call Release, the reference counter will be 0 and COM object will be disposed.

Aaron
+9  A: 

The contract with COM is anytime you are handed an object from a function like this, such as CoCreateInstance(), QueryInterface() (which is what CoCreateInstance() ultimately calls), etc, the callee always calls AddRef() before returning, and the caller (you) always Release() when you are done.

You can use CComPtr<> to make this simpler, and it just does the right thing.

Now if you need to hand this pointer out to another object that expects it to be usable beyond the lifetime of your object, then you need to call AddRef() before giving it out.

I recommend Essential COM by Don Box for further reading on this topic.

jeffamaphone
Although it's 12 years old, 'Essential COM' still keeps giving. Even as a .NET guy I still go back and dip into it.
Kev
+1 (since it cannot be more) for Essential COM. Should note that section "Resource Management and IUnknown" (p53) tells you everything you need to know to get reference counting 100% right.
Richard