malloc and constructors in c++ -
is possible pass parameters constructor of class inside constructor of class using malloc? can new. need same thing malloc: (if not make sense, consider using custom allocator instead of malloc)
class a_class ... { public: b_class *b; ... a_class: ... { b = new b_class (c1, c2, c3); } // end of constructor } now malloc:
class a_class ... { public: b_class *b; ... a_class: ... { b = (b_class*) malloc (sizeof(*b)); ??????????????? } }
malloc allocates raw memory. there's no point in trying pass constructor arguments because doesn't call constructors.
if have work raw memory, construct object in allocated raw memory using "placement new" syntax
... void *raw_b = malloc(sizeof *b); b = new(raw_b) b_class(c1, c2, c3); // <- placement new ... numerically, value of b same raw_b, i.e. possible without raw_b pointer. prefer way, intermediate void * pointer, avoid ugly casts.
be careful when destroying such objects, of course. custom allocation requires custom deletion. can't delete b in general case. symmetrical custom deletion sequence involve explicit destructor call followed raw memory deallocation
b->~b_class(); // <- explicit destructor call free(b); p.s. might consider going different route: overloading operator new/operator delete in class instead of spelling out custom allocation explicitly every time need create object.
Comments
Post a Comment