Search code examples
c++gccg++destructorplacement-new

destructor on placement-new


Is there a pattern to automatically call a destructor of a placement-new initialized object on the stack when it exits scope? I want to skip the need to memorize to call the destructor explicitly. Or, is there a different method than the placement-new to construct a stack based object with a variable size data[] tail? I use g++.

/* g++ f.cpp -o f.exe */
/* 8< --- f.cpp ----  */
#include <stdio.h>
#include <stdlib.h> 
#include <string>
class aclass {
public:
    aclass(int size) : size_(size) {};
    ~aclass() { /* do something */ };
    int size_;
    char data[0];
};

void f(int size)
{
    char v[sizeof(aclass) + size];
    aclass *p = new(static_cast<void*>(&v)) aclass(size);
    p->~aclass();
}

int main(int argc, char **argv)
{
    f(10);
    f(100);
    return 0;
}

Solution

  • You can create a wrapper class like this:

    template <typename T>
    class Foo {
        private:
            T *m_ptr;
        public:
            Foo(void *area, int size) {
                m_ptr = new(area) T(size);
            }
            Foo(const Foo &) = delete;
            ~Foo() {
                m_ptr->~T();
            }
    
            void operator=(const Foo &) = delete;
    
            T *operator->() {
                return m_ptr;
            }
    };
    

    Usage:

    void f(int size) {
        char v[sizeof(aclass)+size];
        Foo<aclass> p(v, size);
    
        p->doSomething(); // call a function from aclass
    }
    

    Note that you're using a GCC extension, as size is not a compile-time constant.

    If it was a compile-time constant, then you could put v into Foo (and size would be a template parameter), so f would be simpler.