Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In COM: should I call AddRef after CoCreateInstance?

Tags:

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

like image 626
mmutilva Avatar asked Mar 14 '09 03:03

mmutilva


1 Answers

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.

like image 164
i_am_jorf Avatar answered Sep 17 '22 20:09

i_am_jorf