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.

4
  • Try making your constants static. Commented Mar 22, 2019 at 0:45
  • 2
    Use std::vector and you will be able to do that. Commented Mar 22, 2019 at 0:46
  • @Gardener The constants differ between objects. Commented Mar 22, 2019 at 2:59
  • @Phil1970 I'm trying to keep implementation tight, fast, and low-memory. Commented Mar 22, 2019 at 2:59

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

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!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.