Question

Is it bad idea to have static CComPtr member variables in an application. Since we cannt control destruction of static variable and it can happen after CoUninitialze .

Was it helpful?

Solution

Provided you take the appropriate precautions, then using a CComPtr as a static member is not inherently evil.

By "appropriate precautions", I mean you should consider:

  • Mutexing access to it;
  • Ensuring that it has been initialised before usage;
  • Maintining a mutexed, static instance count for your own class;
  • Ensuring that CComPtr::Release is called in your class' own FinalRelease method when the instance count reaches zero.

OTHER TIPS

it is a bad idea anyway

As Sergey said in his comment, I think it is bad. Destructors of static objects are called after main terminates as explained in section§ 3.6.3 of the C++03 standard:

Destructors (12.4) for initialized objects of static storage duration (declared at block scope or at namespace scope) are called as a result of returning from main and as a result of calling exit (18.3). These objects are destroyed in the reverse order of the completion of their constructor or of the completion of their dynamic initialization. If an object is initialized statically, the object is destroyed in the same order as if the object was dynamically initialized. For an object of array or class type, all subobjects of that object are destroyed before any local object with static storage duration initialized during the construction of the sub- objects is destroyed.

and as demoed here: http://www.geeksforgeeks.org/static-objects-destroyed/.

But CoUninitialize which cleans the COM library on the main thread is called before Main terminates. CoUninitialize will clean up all remaining resources as explained in the msdn documentation. We should call the Release method of COM objects before CoUninitialize is called because they won't exist anymore after and therefore we should make sure that calls to CComPtr destructor happen before CoUninitialize is called. Therefore a CComPtr should not be made static.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top