Search code examples
c++visual-c++comfactory-pattern

Is using a global object as a COM class factory legal?


In an out-proc COM server I need a class factory that I will pass to CoRegisterClassObject(). CreateInstance() will only use new to create object instances and need no stored data. LockServer() will modify shared lock counter not specific to the factory instance.

So in fact I don't need to store any distinct data inside factory and having only one object will do just fine. Also I don't want to take care of that object lifetime. This is why I'm tempted to declare the factory as a global variable (with refcount set to 1 in constructor):

//Server.cpp
CMyFactory factory;

Once I do that I'm no longer satisfied with delete this inside Release() - that code should never run under normal conditions (refcount starts at 1 and never reaches zero) and if it runs it leads to undefined behavior. So I think of removing the ref counter from the factory and implementing AddRef() and Release() like this:

ULONG CMyFactory::AddRef()
{
   return 1;
}
ULONG CMyFactory::Release()
{
   return 1;
}

So reference counting will just have no side effects, there's no delete this.

Will the described implementation be legal? Will it cause any problems?


Solution

  • As long as you control the process lifetime on different mean, this is accepted. delete this in this case is disaster as the object is global not a dynamic one.