|
Boost : |
From: shiwei xu (xushiweizh_at_[hidden])
Date: 2008-05-06 22:47:00
Your question is very interesting. I thought it before. In fact I don't know
a perfect solution. If the constructor of an object throws, should the
destructor be called?
class Foo
{
private:
A m_a;
B m_b;
C m_c;
public:
Foo() {
m_a.init();
m_b.init();
thow std::exception("error");
m_c.init();
}
~Foo() {
...
}
};
Suppose we initialized m_a and m_b. m_c was uninitialized when the exception
throws. If the destructor is called, it may cause a crash. If the destructor
isn't called, the allocated memory of m_a and m_b will be leaked.
I choose to call the destructor because I think that a crash is easy to be
detected and be solved.
On Wed, May 7, 2008 at 9:34 AM, Steven Watanabe <watanabesj_at_[hidden]>
wrote:
> AMDG
>
> shiwei xu wrote:
> > typedef void (*DestructorType)(void* data);
> >
> > concept GCAllocator
> > {
> > // Allocate memory without given a cleanup function
> > void* allocate(size_t cb);
> >
> > // Allocate memory with a cleanup function
> > void* allocate(size_t cb, DestructorType fn);
> >
> > // Cleanup and deallocate all allocated memory by this GC Allocator
> > void clear();
> >
> > // Swap two GCAllocator instances
> > void swap(GCAllocator& o);
> > };
> >
>
> I have a question about exception safety. Suppose that
> I specify a destructor when I allocate memory, and then,
> the constructor of the object throws. Is there any way
> to prevent the destructor from being called, given this interface?
> Otherwise, the destructor might end up being called on
> an object that was never initialized.
>
> In Christ,
> Steven Watanabe
>
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk