Into

Modules

Documentation

classPiiSharedObject

#include <PiiSharedObject.h>

A shared object.

Description

Shared objects are useful when multiple pointers to a single memory location are concurrently in use. With a shared object, it is possible that the users of the memory location are unaware of each other. Each user just calls reserve() when it starts using the pointer and release() after it no longer needs it. Each reserve() call increases and each release() call decreases a reference counter. When the counter reaches zero, the object is automatically deleted. This type of explicit sharing provides minimum computational overhead but may not be the most convenient way to the programmer. A typical usage scenario is as follows:

 class MyObject : public PiiSharedObject { ... };

 // Sender creates the pointer and passes it.
 MyObject* obj = new MyObject;
 receiver.takeThis(obj);
 otherReceiver.takeThis(obj);
 // This may delete the object. You don't know, so don't fiddle with
 // it any more.
 obj->release();

 //in the receiver, we reserve the pointer for later use:
 void Receiver::takeThis(MyObject* obj)
 {
   internalVariable = obj->reserve();
   doWhatEverNeeded();
 }

Once "Receiver" does not need the pointer any more, it calls internalVariable->release() and forgets about the pointer.

Usually, it is easier to use implicit sharing. For this, the PiiSharedPtr class can be used.

PiiSharedObject is thread safe. Its memory overhead is one integer for the reference counter (plus a vtable pointer, which you most likely had anyway).

Constructors and destructor

Create a new shared object.

virtual

Virtual destructor.

Public member functions

int

Get the number of references to this object.

int

Releases the object.

int

Reserves the object for use.

void
(
  • int cnt
)

Set the number of references to cnt.

Function details

  • PiiSharedObject

    ()
    [inline]

    Create a new shared object.

    The reference counter is initialized to one.

  • virtual ~PiiSharedObject

    ()
    [virtual]

    Virtual destructor.

    This ensures the delete operator always destroys the bottommost derived class.

  • int references

    ()
    [inline]

    Get the number of references to this object.

  • int release

    ()
    [inline]

    Releases the object.

    The reference counter is decremented by one. Once it reaches zero, the object will be deleted.

  • int reserve

    ()
    [inline]

    Reserves the object for use.

    The reference counter is incremented by one and returned.

    Returns

    the reference count after the call

  • void setReferences

    (
    • int cnt
    )
    [inline]

    Set the number of references to cnt.

Notes (0)

Add a note

Not a single note added yet. Be the first, add yours.