1

So, I have an object with a constructor. This object doesn't support empty constructors because there are constants that must be assigned in the constructor. Something like this:

class Object {
public:
    const int foo;

    Object(int f) : foo(f) {
        // other stuff
    }
}

Now I have another function that keeps a dynamically allocated array of objects.

Object* objects;

I need to be able to allocate this memory using new[] and delete[] but also use the constructor. I can't seem to figure out how to do this.

Something like this would be ideal

objects = new Object[numObjects];
for (int i = 0; i < numObjects; ++i) {
    object[i](foos[i]);
}

I could use malloc and free, then new the objects in place, but that would be non ideal as I would have to loop through the objects in the destructor and manually destruct them, then free the memory. Seems messy.

Thor Correia
  • 1,159
  • 1
  • 12
  • 20

1 Answers1

1

You could use list initialisation:

objects = new Object[3]{1, 2, 3};

But this only works with a constant size array.

I could use malloc and free, then new the objects in place

This is indeed exactly the way to create an array of dynamic length containing objects of a non-default-constructible type. Except instead of malloc, it would be more idiomatic to allocate an array of std::byte with new[]. This is also how to allocate an array of certain number of objects that you would like to create later.

But there's no need to write that yourself, since the standard library provides you with std::vector, which does this for you:

std::vector<Object> mycars(numObjects, Object(42));
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • I don't want to use std::vector in the interest of speed and memory. I might go with malloc. Perhaps I'll do some bench-testing with both implementations and see what I get. Thanks! – Thor Correia Mar 22 '19 at 02:58