Kernel SDK Developer's Guide > Basic Operations > Working with Smart Pointers > Example of a Typified Smart Pointer
Example of a Typified Smart Pointer

The OdSmartPtr class is a typified smart pointer for classes derived from the OdRxObject. You must define a new type for it using the (typedef) statement. For example, the class definition:

class MyObj : public OdRxObject
{
 public:
   MyObj();
   ~MyObj();
};

typedef OdSmartPtr<MyObj> MyObjPtr;

The testing function has the following implementation:

void Test()
{
  MyObjPtr pSmart0 = OdRxObjectImpl<MyObj>::createObject();

  MyObjPtr* pObj = pSmart0.get();
  odPrintConsoleString(L"\nRefs=%d", pObj->numRefs());                   // 1

  MyObjPtr pSmart1 = pSmart0;                                            // = pObj
  MyObjPtr pSmart2 = pSmart1;                                            // = pObj
  odPrintConsoleString(L"\nRefs=%d", pObj->numRefs());                   // 3

  MyObjPtr pSmart3;                                                      // = null

  odPrintConsoleString(L"\n(p1==Null)?%d", pSmart1.isNull());            // 0 (false)
  odPrintConsoleString(L"\n(p3==Null)?%d", pSmart3.isNull());            // 1 (true)

  pSmart3.attach(pObj)                                                   // = pObj
  odPrintConsoleString(L"\nRefs=%d", pObj->numRefs());                   // 3

  OdRxObjectImpl<MyObj> my;

  pSmart3.attach(&my)                                                    // = my
  odPrintConsoleString(L"\nRefs=%d", pObj->numRefs());                   // 2

  odPrintConsoleString(L"\n(p1==p2)?%d", (pSmart1 == pSmart2));          // 1 (true)
  odPrintConsoleString(L"\n(p1==p3)?%d", (pSmart1 == pSmart3));          // 0 (false)

  pSmart2.detach()                                                       // = null
  pSmart3.detach()                                                       // = null
  odPrintConsoleString(L"\nRefs=%d", pObj->numRefs());                   // 2

  pSmart1.release();                                                     // = null
  odPrintConsoleString(L"\nRefs=%d", pObj->numRefs());                   // 1

  pSmart0.release();                                                     // 0 - object is destroyed
}

See Also

Working with Smart Pointers

Implementing Smart Pointers

Copyright © 2002 – 2020. Open Design Alliance. All rights reserved.