Calling delete on automatic objects
<p>Consider the following c++ code:</p>

<pre><code>class test
{
public:
    int val;

    test():val(0){}
    ~test()
    {
        cout &lt;&lt; "Destructor called\n";
    }
};

int main()
{
    test obj;
    test *ptr = &amp;obj;
    delete ptr;

    cout &lt;&lt; obj.val &lt;&lt; endl;

    return 0;
}
</code></pre>

<p>I know delete should be called only on dynamically allocated objects but what would happen to obj now ?  </p>

<p>Ok I get that we are not supposed to do such a thing, now if i am writing the following implementation of a smart pointer, how can i make sure that such a thing does't happen.</p>

<pre><code>class smart_ptr
{
public:
    int *ref;
    int *cnt;

    smart_ptr(int *ptr)
    {
        ref = ptr;
        cnt = new int(1);
    }

    smart_ptr&amp; operator=(smart_ptr &amp;smptr)
    {
        if(this != &amp;smptr)
        {
            //  House keeping
            (*cnt)--;
            if(*cnt == 0)
            {
                delete ref;
                delete cnt;
                ref = 0;
                cnt = 0;
            }

            //  Now update    
            ref = smptr.ref;
            cnt = smptr.cnt;
            (*cnt)++;
        }
        return *this;
    }

    ~smart_ptr()
    {
        (*cnt)--;
        if(*cnt == 0)
        {
            delete ref;
            delete cnt;
            ref = 0;
            cnt = 0;
        }
    }
};
</code></pre>
