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?

Jack Humphries
  • 13,056
  • 14
  • 84
  • 125

1 Answers1

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.

bolov
  • 72,283
  • 15
  • 145
  • 224