收录日期:2021/02/27 20:06:02 时间:2009-03-14 03:17:44 标签:c++,com

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

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.

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.

One exception to the rule: CComObject<>::CreateInstance() does NOT perform an AddRef. You must do that after you call it.