dimanche 1 novembre 2015

std::unique_ptr

In my code for numerical physics, I need to create an array of Derived objects using the unique_ptr with their type being the Base class. Normally, I would have:

// Header file of the Base class
class Particle{
public:
    Particle();             // some constructor
    virtual ~Particle();    // virtual destructor because of polymorphism
    virtual function();     // some random function for demonstration
};

// Header file of the Derived class
class Electron : public Particle{
public:
    Electron();
    // additional things, dynamic_cast<>s, whatever
};

Later in my code, to create an array of Derived objects with the Base type pointer, I would do

Particle* electrons = new Electron[count];

The advantage is that I am able to use the array in a really convenient way of electrons[number].function(), because the incremental value in [] is actually the address of the memory that points to the proper instance of the object Electron in the array. However, using raw pointers gets messy, so I decided to use the smart pointers.

Problem is with the definition of the Derived objects. I can do the following:

std::unique_ptr<Particle, std::default_delete<Particle[]>> electrons(new Electron[count]);

which creates the array of polymorphic Electrons and uses even the proper call of delete[]. The problem lies in the way of calling the specific objects of the array, as I have to do this:

electrons.get()[number].function();

and I don't like the get() part, not a little bit.

I could do the following:

std::unique_ptr<Particle[]> particles(new Particle[count]);

and yes, call the instances of Particle type in the array with the

particles[number].function();

and everything would be fine and dandy, except for the part that I am not using the specific details of the class Electron, therefore the code is useless.

And now for the funny part, let's do one more thing, shall we?

std::unique_ptr<Particle[]> electrons(new Electron[count]);

BOOM!

use of deleted function ‘std::unique_ptr<_Tp [], _Dp>::unique_ptr(_Up*) [with _Up = Electron; <template-
 parameter-2-2> = void; _Tp = Particle; _Dp = std::default_delete<Particle []>]’

What is going on?

Aucun commentaire:

Enregistrer un commentaire