Discussion:
CoCreateInstance vs. new
(too old to reply)
d***@gmail.com
2008-06-14 22:50:54 UTC
Permalink
In a code review, I encountered a method that is supposed to create
and return a COM interface. In the implementation of this method, the
author used the 'new' operator on the C++ class that implements the
COM interface (this C++ class is in the same cpp file and DLL). Then,
the author called AddRef, and returned the class instance from this
method.

This obviously raised red flags, but what are the best arguments for
calling CoCreateInstance (vs. new)?

In this particular case, there was no threading/apartment concerns
either, but I am generally interested in understanding what are the
primary gotchas code like this would encounter.

Any comments/experiences?
Helge Kruse
2008-06-20 16:26:34 UTC
Permalink
Post by d***@gmail.com
In a code review, I encountered a method that is supposed to create
and return a COM interface. In the implementation of this method, the
author used the 'new' operator on the C++ class that implements the
COM interface (this C++ class is in the same cpp file and DLL). Then,
the author called AddRef, and returned the class instance from this
method.
This obviously raised red flags, but what are the best arguments for
calling CoCreateInstance (vs. new)?
In this particular case, there was no threading/apartment concerns
either, but I am generally interested in understanding what are the
primary gotchas code like this would encounter.
Any comments/experiences?
You use CoCreateInstance to ask COM to create an object. Usually it detects what DLL will fulfill the request and calls the
corresponding DllGetClassObject (in case of inproc server). when you have to implement DllGetClassObject you will have to create an
(C++-)object that will implement the requested interface. You create an object at the hep with 'new'.

So, what's the problem?

An argument for CoCreateInstance is that the COM queries the registry to get the correct object with all information for aparment
and probably create it remotely. But there are situations, where an immediate creation with 'new' is OK.

Regards,
Helge

Loading...