0

I want to create an array/vector (indifferent to which one) of class instances. I have the following constraints:

  1. Each instance is constructed with a different argument (e.g., Item(0), Item(1), Item(2), ...).
  2. The Item class has both its copy and move constructors deleted.

Constraint #2 above seems to rule out using an std::vector since the vector would need to either copy or move the enqueued instances when it resizes its backing store.

This leaves me with an array. For both a C-style array and std::array, there does not seem to be any way to specify custom constructors for items in the array, so I can't custom construct items in-place in array indices. The only other option is to create an array of pointers and do array[0] = new Object(0);, array[1] = new Object(1);, array[2] = new Object(2);, but this is messy since it allocates memory on the heap rather than just the stack and requires me to explicitly free memory.

Is there a way to do this?

4
  • Just to clarify: what you want is to pass the index of the object in the array to its constructor? Commented May 20, 2020 at 3:55
  • do you need to resize the container after its creation? Commented May 20, 2020 at 3:56
  • @Kein That happens to be true, but I would also want to know how to do this when that is not the case. Commented May 20, 2020 at 4:57
  • @bolov No, I know the size upfront. Commented May 20, 2020 at 4:58

1 Answer 1

3

Given

struct Item
{
    Item(int);
    Item(const Item&) = delete;
    Item(Item&&) = delete;
};

You have some options:

smart pointers

You can use smart pointers, in this case std::unique_ptr:

auto test()
{
    std::vector<std::unique_ptr<Item>> v;

    v.emplace_back(std::make_unique<Item>(1));
    v.emplace_back(std::make_unique<Item>(2));
    v.emplace_back(std::make_unique<Item>(3));
}

std::array

If you do not need to resize or move the container you can use std::array (since C++17):

auto test2()
{
    std::array<Item, 3> arr{1, 2, 3};
}

This works since C++17 because of the new temporary materialization rules.

Sign up to request clarification or add additional context in comments.

4 Comments

Wow, using temporary materialization to do this looks great! For my own knowledge, can we do this with a C array?
Additionally, is there a way to do this when I don't know the argument values (1, 2, 3 above) at compile time?
@JackHumphries: auto test3(int a, int b, int c) { std::array<Item, 3> arr{a, b, c}; } is fine.
It also looks like stackoverflow.com/questions/3763846/… could be useful here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.