Allocate Space for unknow class

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?.

So can you not just use sizeof(MyDerivedType):?
Last edited on
you can override the new operator like:
1
2
3
4
5
6
7
8
9
10
class CObj
{
public:
  CObj();
  virtual ~CObj();

public:
  void *operator new(const size_t size);
  void operator delete(void *const p);
};
where you provide the memory and free it

EDIT: It's ok to use that as a base class for those classes in question since 'size' is appropriate
Last edited on
closed account (1yR4jE8b)
What about using 'placement new' on a void buffer?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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;
}

How do you know if 1024 bytes is large enough for a Foo?

And if it's much smaller, isn't that a waste of space?
Topic archived. No new replies allowed.