Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use C++ "operator new" rather than CoCreateinstance to create a COM object?

Tags:

c++

com

this is probably a noob COM question, but googling this raises more questions than providing answers:

Is it safe to use "operator new" instead of CoCreateInstance for a local COM instance?

What I've done:

  1. I implemented the IOperationsProgressDialog interface http://msdn.microsoft.com/en-us/library/windows/desktop/bb775368(v=vs.85).aspx by using public inheritence and thereby also implemented the IUnknown interface.

  2. I created an instance via "new RecyclerProgressCallback" and put it into a COM-Ptr for life-time management. "RecyclerProgressCallback" is the name of my derived class.

  3. I'm using this instance in IFileOperation::SetProgressDialog http://msdn.microsoft.com/en-us/library/windows/desktop/bb775803(v=vs.85).aspx

Summary: My approach "seems" to work, but I don't trust it, there's just too much disconcerting information around COM object creation to rely on the observable behavior only.

Are there any subtle risks, fallacies or other problems? Thanks!

like image 967
Zenju Avatar asked Oct 24 '12 15:10

Zenju


2 Answers

I've even put them on the stack. Andrey's answer (now deleted) incorrectly suggested that it is unsafe, because you bypass COM reference counting. This is faulty reasoning. COM doesn't count references; it delegates the responsibility to you. You have to call delete, or free(), or whatever your language uses, after COM calls your Release method on its last interface. The important word is after. Not when, because you're not obliged to do so immediately.

Similarly, CoCreateInstance is a long detour because COM is language-neutral and doesn't know whether an object must be created with malloc or new. You do, so just bypass the whole COM logic.

like image 144
MSalters Avatar answered Oct 05 '22 14:10

MSalters


It depends what exactly you are instantiating. When you are supposed to provide a COM pointer noone asks you whether it is instantiated with COM API, or new, or it can sometimes be even object on stack (provided that you manage to ensure it is not destroyed on stack before all references are released).

So the answer is yes, you can use new and it would be fine. However, it should be a valid COM interface anyway, it should implement reference counting and QueryInterface the way COM objects do.

like image 43
Roman R. Avatar answered Oct 05 '22 12:10

Roman R.