Boost logo

Boost :

From: David Abrahams (dave_at_[hidden])
Date: 2002-09-04 16:23:31


From: "Bryan Ross" <bross_at_[hidden]>

> Well, if that isn't just darn peculiar behavior. It calls the
> destructor, but doesn't actually deallocate the space for the object.
>

It's as "deallocated" as it comes. You're just seeing a dangling reference
to some stack memory. The following demonstrates that the memory gets
re-used:

#include <iostream>
#include <string>

static int cnt = 42;

struct X {
    X() : x(cnt++) { std::cout << "X(): " << &x <<std::endl;}
    ~X() { std::cout << "~X(): " << &x << std::endl; x = -666; }
    int x;
};

using namespace std;
struct hold
{
    hold(const X& i) : x(i) {}
    const X& x;
};

X f()
{
    return X();
}

hold* ff()
{
    return new hold(f());
}

int main(int argc,char** argv)
{
    hold* h[3];
    for (int i = 0; i < 3; ++i)
        h[i] = ff();

    cout << h[0]->x.x << std::endl;
    cout << h[1]->x.x << std::endl;
    cout << h[2]->x.x << std::endl;
    delete h[2];
    delete h[1];
    delete h[0];
    return 0;
}

-----------------------------------------------------------
           David Abrahams * Boost Consulting
dave_at_[hidden] * http://www.boost-consulting.com


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk