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;
}