Resource allocation and automatic deallocation
<p>In my application I got many instances of <strong>class CDbaOciNotifier</strong>. They all share a pointer to only one instance of <strong>class OCIEnv</strong>.</p>

<p>What I like to achieve is that allocation and deallocation of the resource <strong>class OCIEnv</strong> will be handled automatically inside <strong>class CDbaOciNotifier</strong>.</p>

<p>The desired behaviour is, with the first instance of <strong>class CDbaOciNotifier</strong> the environment will be created, after that all following notifiers use that same environment. With the destruction of the last notifier, the environment will be destroyed too (call to custom deleter).
<strong>Later on, this cycle can start again with the creation of a new environment.</strong></p>

<p>What I've got so far (using a static factory method to create notifiers):</p>

<pre><code>#pragma once

#include &lt;string&gt;
#include &lt;memory&gt;
#include "boost\noncopyable.hpp"

class CDbaOciNotifier : private boost::noncopyable
{
public:

    virtual ~CDbaOciNotifier(void);

    static std::auto_ptr&lt;CDbaOciNotifier&gt; createNotifier(const std::string &amp;tnsName, const std::string &amp;user, const std::string &amp;password);

private:
    CDbaOciNotifier(OCIEnv* envhp);

    // All notifiers share one environment
    static OCIEnv* m_ENVHP;

    // Custom deleter
    static void freeEnvironment(OCIEnv *env);

    OCIEnv* m_envhp;
};
</code></pre>

<p>CPP:</p>

<pre><code>#include "DbaOciNotifier.h"

using namespace std;

OCIEnv* CDbaOciNotifier::m_ENVHP = 0;

CDbaOciNotifier::~CDbaOciNotifier(void)
{
}

CDbaOciNotifier::CDbaOciNotifier(OCIEnv* envhp)
                :m_envhp(envhp)
{

}

void CDbaOciNotifier::freeEnvironment(OCIEnv *env)
{
    OCIHandleFree((dvoid *) env, (ub4) OCI_HTYPE_ENV);
    *env = null;
}

auto_ptr&lt;CDbaOciNotifier&gt; CDbaOciNotifier::createNotifier(const string &amp;tnsName, const string &amp;user, const string &amp;password)
{
    if(!m_ENVHP)
    {
        OCIEnvCreate( (OCIEnv **) &amp;m_ENVHP, OCI_EVENTS|OCI_OBJECT, (dvoid *)0,
            (dvoid * (*)(dvoid *, size_t)) 0,
            (dvoid * (*)(dvoid *, dvoid *, size_t))0,
            (void (*)(dvoid *, dvoid *)) 0,
            (size_t) 0, (dvoid **) 0 );
    }

    //shared_ptr&lt;OCIEnv&gt; spEnvhp(m_ENVHP, freeEnvironment); ...got so far...

    return auto_ptr&lt;CDbaOciNotifier&gt;(new CDbaOciNotifier(m_ENVHP));
}
</code></pre>

<p>I'd like to avoid counting references (notifiers) myself, and use something like shared_ptr.</p>

<p>Do you see an easy solution to my problem? </p>
