PRB: Unhandled Exception Using COM Smart Pointers with VC++

ID: Q192651


The information in this article applies to:
  • Collaboration Data Objects (CDO), versions 1.1, 1.2, 1.21
  • Microsoft Visual C++, 32-bit Editions, versions 5.0, 5.0sp1, 5.0sp2, 5.0sp3


SYMPTOMS

Using smart pointers with Visual C++ version 5.0, generated by including a type library with #import, it is possible to experience an unhandled exception error in your application. A common symptom is having near identical code for an object model, such as Collaboration Data Objects (CDO) that works fine in Visual Basic, but not from C++.


CAUSE

Reference counting is being handled improperly.


RESOLUTION

When reassigning a smart pointer it is important to first set the pointer to NULL. This causes the smart pointers implementation to properly release the previous object before assigning the pointer to the new object. This occurs when you compile and link with Visual C++ 6.0.


MORE INFORMATION

Steps to Reproduce Behavior

This problem can appear in any call in which a Component Object Model (COM) smart pointer is reused. The following example reproduces the problem:

   try {

        _SessionPtr pSession("MAPI.Session");
        pSession->Logon();

        FolderPtr   pFolder = pSession->Inbox;
        MessagesPtr pMessages = pFolder->Messages;
        MessagePtr  pMessage = pMessages->GetFirst();
        _bstr_t body;

        while (pMessage != NULL) {
            body = pMessage->Text;
            _tprintf("%s\n", (LPCTSTR)body);
            pMessage = pMessages->GetNext();
        }

    } catch (_com_error &e) {
        dump_com_error(e);
    } 
The preceding code fails on the following line because you are now reassigning the smart pointer without first releasing the underlying object:

   pMessage = pMessages->GetNext(); 
For the preceding code to work, that line should be replaced by the following two lines of code:

   pMessage = NULL;
   pMessage = pMessages->GetNext(); 
It is also a good idea to set the pointers to NULL at the end of your code. This must be done if you are going to call the CoUninitialize function in the same scope as the smart pointers.


REFERENCES

Inside COM, Dale Rogerson, Microsoft Press, pg. 218.

Additional query words:

Keywords : kbole kbCDO121 kbCOMt kbMsg kbVC kbGrpMsg
Version : WINDOWS:1.1,1.2,1.21; winnt:5.0,5.0sp1,5.0sp2,5.0sp3
Platform : WINDOWS winnt
Issue type : kbprb


Last Reviewed: November 8, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.