views:

108

answers:

2

I have created a COM componenet named as Test.dll in that i have created an interface IDiscover.

Now i came to 2 ways of allocating the memory as

  IDiscoverPtr id(__uuid(TestClass)); and Test::IDiscover *id=NULL;

What is the differnce between these two....Any Information is appreciated..

Thanks in Advance

+2  A: 

First one is a Smart Pointer and the Second one is a normal pointer.

You don't need to worry about Releasing a Smart Pointer whereas you have to explicitly Release() a normal COM Interface Pointer.

For more details on Smart Pointers, Look Here

Apart from that, the first one will try to find a GUID from registry for your Class named TestClass and will try to create an Instance of this class through CoCreateInstance API Call. It will try to get the IDiscover interface pointer through the said CoCreateInstance call and will throw an error if it fails to do so. On successful execution of the line IDiscoverPtr id(__uuid(TestClass));, you should have a valid IDiscover interface pointer in id.

The Second one is simply declaration of an Interface pointer, nothing else. You will have to instantiate it yourself through (most of the times) CoCreateInstance or one of it's variants.

Aamir
+1  A: 

The first variant is a smart pointer, the second one is a raw (ordinary pointer). The smart pointer will call IUnknown::Release() of the connected object when it itselft goes out of scope. The raw pointer will not do so and you will possibly get a memory leak unless you call IUnknown::Release() of the conected object explicitly at a suitable moment.

The first variant will try to instantiate the COM object upon its own construction (since you use the constructor parameterised with the class id) and throw an exception if that can't be done. See sources for _com_ptr_t (comip.h) for details. The second variant will give you a pointer initialized to null - not connected to any object.

Smart pointers for COM objects have a set of member function useful for instantiating objects and calling QueryInterface() - this can often reduce the amount of code needed to write. With a raw pointer you will have to call CoCreateInstance() with a handful of parameters most of which you will set to default values and this will force you to write more code. Again see the comip.h for the full sources of _com_ptr_t - they are quite readable.

The general recommendation is to use smart pointers unless you have real reasons to do otherwise.

sharptooth
So we dont need to call CoCreate() when using __uuid("<classname">) right....???
Cute
With a smart pointer you can either use its constructor taking the __uuid or use a default constructor and call the _com_ptr::CreateInstance() method or call global CoCreateInstance() - whatever is more suitable. The latter will not throw an exception but rather return an HRESULT.
sharptooth