Main Page Namespace List Class Hierarchy Compound List Compound Members

# ZThread::SharedInstance Class Template Reference

`#include <SharedInstance.h>`

List of all members.

## Public Methods
| SharedInstance ()
| ~SharedInstance ()
SHARED* | operator-> ()
const SHARED* | operator-> () const

## Detailed Description

### template<class SHARED> class ZThread::SharedInstance

Author:
  Eric Crahen

Date:
  09-21-2000

Version:
  1.1.0

This template creates a counted Singleton instance of type SHARED. Its a combination of the handle-body idiom and a Singleton. It will only delete the Singleton after all instances of it are out of scope. This is a bit more ideal than using a pattern like the SingletonDestroyer for certain situations. The Singleton portion of this pattern remains hidden from the user.

The SingletonDestroyer, an alternative approach, makes no guarantee as to what order or when the Single is destroyed. This becomes problematic when Singleton's refer to one another explicitly or implicitly through shared data. The Singleton can be deleted in an inappropriate order or at an unexpected time - freeing data still in use by another Singleton that has not been destroyed yet. This leads to access violations and in some cases memory leaks.

The ObjectLifetimeManager used in the ACE framework presents a much more controlled and complex solution. However, for small, simple applications that include co-dependent Singleton's, or short lived Singleton's this is a good solution.

@example This example demonstrates how to use this pattern to create a a single SocketPump object that will drive the low level i/o of a Socket implementation in a separate thread. The details of the i/o are left out for brevity.

class SocketImpl {

... SharedInstance<SocketPump> _pump;

public: SocketImpl(...) { _pump.register(this); } virtual ~SocketImpl(...) { _pump.unregister(this); } ... };

The SocketPump going to refer to the same SharedInstance for all SocketImpl objects. It will be destroyed when all the SocketImpl go out of scope. The SocketPump is automatically created & started and stopped & destroyed as necessary.

## Constructor & Destructor Documentation

SharedInstance ( | )`[inline]`

| Update the shared instance count, instantiate the object if necessary

~SharedInstance ( | )`[inline]`

| Decrements the shared instance count, clean up the shared object if the count drops to 0

## Member Function Documentation

const SHARED * operator-> ( | ) const`[inline]`

| Provide access to the shared instance Returns: SHARED* object instance being shared

SHARED * operator-> ( | )`[inline]`

| Provide access to the shared instance Returns: SHARED* object instance being shared

The documentation for this class was generated from the following file:

- SharedInstance.h