Click to See Complete Forum and Search --> : com


avsramesh
June 19th, 2002, 09:04 AM
What is the advantage of using CComPtr class. If I use it,is it required for me to call the Release() function of it.
Ex:
CComPtr <IAdd> pAdd;
pAdd->Addition();

pAdd.Release();// Is this really required or not.

claudiu_t
June 19th, 2002, 02:13 PM
Hi,

The answer is NO. As you already have read in the doc the CComPtr class is a smart pointer class, whose purpose is - besides others - to remove the necessity of Release() call.

Now, if you can write a simple console app such as:


void main() {
::CoInitialize(NULL);

CComPtr<ISomeInterface*> ptr = NULL;
ptr->CreateInstance(CLSID_Library);

// consume ptr

::CoUninitialize();
}


you may notice an error message at run-time! if you add the line


ptr->Release();


just before the ::CoUninitialize() call the error message disappears. Oops! it seems our smart pointer class is not working properly. In fact is just a variable scope issue: our ptr variable live after the ::CoUninitialize() call and his destructor is called only after this, which is perfectly correct. The workarround is to place the main code in a block, like this:


void main() {

::CoInitialize(NULL);

{
CComPtr<ISomeInterface*> ptr = NULL;
// rest of the code here
}

::CoUninitialize();
}


which obviously makes useless the ptr->Release() call.

HTH regards,
Claudiu