Bulk-allocating objects with calling new operator once?

Viewed 1231

I understand the basics about overloading the new operator for a particular class. However, one thing I do not understand if its possible. Say I have a class like this:

class X{
    int a;
    long b;
    float c;
}

and I wish to pre-create 100 X objects at the very beginning of my program. I would like to call the new operator just the once, to allocate (at least) (4 + 4 + 4?) x 100 = 1200 bytes. Then, whenever X::new() is called, instead of new() (or malloc()) being called, I will return the empty "shell" of an X object and then a, b and c are simply assigned to the data members.

How would I go about doing this? The emphasis on my question is that memory is only taken from the kernel once, when I reserve 1200 bytes for 100 X objects. After the beginning of my program I want the bare minimum to be executed when retrieving an X object "shell"?

3 Answers

This is almost always a bad idea (see my paper, "Reconsidering Custom Memory Allocation", for a detailed discussion of why; in short, general-purpose allocators already optimize for the cases that custom allocators attempt to optimize).

Whenever you consider using a custom allocation scheme, you should ask yourself the following: have you actually measured the performance impact of using the default allocator (it is not always that much, and not clearly worth the risk of errors, etc.)? If it's actually the bottleneck, have you tried alternate allocators like Hoard, tcmalloc, or jemalloc?

Related