Basic COM   «Prev  Next»

Debug Class Factory - Exercise

Objective: Identify and fix three bugs in the following code.

Instructions

The following code contains three bugs.
  1. Identify the errors
  2. Explain how best to fix them.

class CO1 : public IF1 { ... }

struct CFO1 : public IClassFactory {
  ULONG m_refcnt;

  HRESULT QueryInterface
    (const IID& riid, VOID **ppv) {

    if (IID_IUnknown ==
   riid || IID_IClassFactory == riid) {

  *ppv = this;
     return S_OK;
    }
    return E_NOINTERFACE;
  }

  ULONG AddRef() { return ++m_refcnt; }

  ULONG Release() {
    if (--m_refcnt == 0) {
       delete this;
       return 0;
    }
    return m_refcnt;
  }

  HRESULT CreateInstance (IUnknown *pOuter, const IID &riid,void **ppv) {
     CO1*pc;
    if (pOuter != NULL) 
   return E_NOAGGREGATION;
    pc = new CO1();
  HRESULT hr = pc->QueryInterface(riid, ppv);
    return S_OK;
  }

  HRESULT LockServer(BOOL fLock) {
    if (fLock) ++g_lock;
    else --g_lock;
  }
  CFO1() { }
};

Exercise scoring

This exercise is worth a total of 15 points; up to 5 points for each bug found.

Exercise submission

Click Submit to submit this exercise to the course.