hi all, in my project came out a problem:
for the sake of avoiding mem defragments and space insurficient, we're not allowed to "new" class in run-time, so i have to pre-allocate space for some objects when initiallizing.
there's the problem: i need a object which is some kind of derieved class A, but i don't know which subclass it would be until run-time, so i don't know what should i declare.
I think placement new might fix the problem (pre-allocate mem, and new a object on it when i know it's type), but it requires a mem manage mechanism that will lead to a lot of modification in the existed project.
So I came for any help from you all, thank you!
Well if you had used the new operator then you would have had to have known the exact type of the object you were creating and therefore you could have obtained its correct size at the point of creation. So I would have thought that you still need to know the exact type of what you are creating at the point when you allocate memory for it, otherwise what constructor will you call?.
#include <iostream>
#include <new>
#include <cstdlib>
struct Foo
{
};
int main()
{
//pre allocate the buffer
void* buff = malloc(1024);
//'place' a Foo in the pre-allocated space
Foo* placementFoo = new (buff) Foo();
//do stuff with objects in the buffer
//. . .
//Free objects in the buffer by manually calling the destructor
placementFoo->~Foo()
//free the buffer when you are done
free(buff);
return 0;
}