Does an equivelent to C++'s placement new exist in C? I mean, can an object be constructed at a specified location in C? Can realloc()
be used for that?
Placement new simply skips allocation and constructs an object in preallocated memory. Since C lacks constructors, there is no need for placement new. I suppose the equivalent would be a pointer typecast, because once you have a pointer, you can act as if an object exists.
Example of carving objects of differing type from a common memory pool:
char *pool = (char *) malloc( 1000 );
char *pen = pool;
foo *obj1 = (foo *) pen;
pen += sizeof (foo);
bar *obj2 = (bar *) pen;
pen += sizeof (bar);
/* etc */
Of course, in doing this, you take responsibility for passing the right pointer to free
, and looking after alignment requirements — just like placement new in C++.
Since C doesn't have anything like a constructor, you can simply take the address and cast it to a pointer to the type you want to use. Of course, you need to ensure proper alignment, or that can fail (but the same is true with placement new in C++).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With