0

I want to make a class factory that can create classes knowing nothing about them (eg no headers included). I created a factory class with map, that stores info about classes (sizeof and pointer to static method) by strings ( map(string, mystruct) ), which is filled from each class.

When factory is producing a class, it allocates raw memory and calls static method, which then calls the default constructor on that memory:

void *ptr = operator new(classSize);
classCCaller(ptr);//void (*classCCaller)(void*)

then inside the static method of that class the following code is executed:

new (ptr) SomeClassConstructor();

The produced class is then put in some container.

Question - is it ok to delete classes, created that way, by

delete p;//SomeClass *p;

or should I manually call destructor and use operator delete on untyped pointer?

1 Answers1

4

No, you have to say p->~SomeClass(); operator delete(ptr);, where p = static_cast<SomeClass*>(ptr).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Does that mean that lines 29 and 35 in the example at [CPlusPlus](http://www.cplusplus.com/reference/new/operator%20new/) are not correct? – SeriousAlexej Jun 23 '15 at 13:47
  • @SeriousAlexej Line 35 is undefined, since the object has never been constructed. That site should be taken with large grains of salt. – molbdnilo Jun 23 '15 at 13:52
  • @SeriousAlexej: [shock horror](http://stackoverflow.com/questions/6520052/whats-wrong-with-cplusplus-com) :-) – Kerrek SB Jun 23 '15 at 14:10