I know I can do new char[n] to create an array of n chars. This works even when n is not a compile time constant.
But lets say
You can use placement new:
#include
struct Test {
size_t size;
char a[1];
static Test* create(size_t size)
{
char* buf = new char[sizeof(Test) + size - 1];
return ::new (buf) Test(size);
}
Test(size_t s) : size(s)
{
}
void destroy()
{
delete[] (char*)this;
}
};
int main(int argc, char* argv[]) {
Test* t = Test::create(23);
// do whatever you want with t
t->destroy();
}