0

I have the following problem. I have unique_ptr to an array of a base class A. Which in pure C++ is no problem to initialize with a pointer to an array of a derived type B. Now with the unique_ptr<A[]> I fail to get this working. I don't see the issue and want to avoid going the custom deleter route. I there something other off with my approach?

struct A {
    virtual ~A() {};
};

struct B : public A {
    int min, max;
};

unique_ptr<A[]> a_arr;

// fails
a_arr.reset(new B[2048]);
a_arr = make_unique<B[]>(2048);

// works
A* a_raw_arr = new B[2048];
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
user1901361
  • 51
  • 1
  • 3

2 Answers2

1

You cannot store elements of a derived type in an array of the base tape because they will not fit. What you can do is to have an array of pointers.

  • 3
    There is no _array of the base type_ in the OP's case. Only a pointer to an array. I would better write something that one _cannot treat an array of derived objects via a pointer to an array of base objects_. – Daniel Langr Sep 15 '20 at 12:34
  • @DanielLangr The unique_ptr is templated against `A[]`. I don't see all the finer impact of it, but it definitely does something array-ish. Personally, I'd rather have an array (or vector) of unique_ptr. – Jeffrey Sep 15 '20 at 12:37
  • @Jeffrey I agree, I just pointed to the misinterpretation. OP does not store objects of `B` into an array of `A`, there is no array of `A` involved. – Daniel Langr Sep 15 '20 at 12:39
1

@ChristopherYeleighton gave you the reason. The way around is to use an array of unique_ptr as opposed to a unique_pointer to an array.

std::unique_ptr<A> a_arr[2048] = {std::make_unique<B>()};

Alternatively, a std::vector of unique_ptr<A> would also work.

The main thing you gain of this is that you are now allowed to have pointers to different derived classes in your a_arr.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
  • 3
    Note that your code will initialize only the first element of `a_arr` to `std::make_unique()`. Other elements will be default-initialized. See, e.g., [Initialization of all elements of an array to one default value in C++?](https://stackoverflow.com/q/1065774/580083) and [How to fill an array of unique_ptr?](https://stackoverflow.com/q/41365505/580083). – Daniel Langr Sep 15 '20 at 12:41