Search code examples
c++new-operatorinitializationalloc

C++ uninitialized array of class instances


I've been searching but couldn't find an answer to this. Is there a way to tell the new operator to not call the class constructors?

MyObject* array = new MyObject[1000];

This will call MyObject() a thousand times! I want to fill the allocated memory myself and do not need any information initialized in the constructor. Using malloc() is not very harmonic C++ code imho.

MyObject* array = (MyObject*) malloc(sizeof(MyObject) * 1000);

Solution

  • The C++ equivalent to malloc is the allocation function operator new. You can use it like so:

    MyObject* array = static_cast<MyObject*>(::operator new(sizeof(MyObject) * 1000));
    

    You can then construct a particular object with placement new:

    new (array + 0) MyObject();
    

    Replace 0 with whichever offset you wish to initialise.

    However, I wonder whether you really want to be doing this dynamic allocation yourself. Perhaps a std::map<int, MyObject> or std::unordered_map<int, MyObject> would suit you better, so that you can create a MyObject at any index.

    std::unordered_map<int, MyObject> m;
    m[100]; // Default construct MyObject with key 100