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