mardi 15 septembre 2020

C++ unique_ptr array of polymorphic type

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];

Aucun commentaire:

Enregistrer un commentaire