dimanche 12 avril 2020

Flexible array member in class with polymorphism

In C99 you can have something like

struct foo
{
    int a;
    int data[];
}; 

And then allocate with foo* f=(foo*)malloc(sizeof(foo)+n) to have a struct where the length of the array is n.

Can one do something similar in C++ when the class is a subclass with virtual functions?

Like foo being a subclass of bar, then do something like std::unique_ptr<bar> f= std::unique_ptr<foo>((foo*)malloc(sizeof(foo)+n))

I know that that code doesn't work as freeing the memory would be done with delete but allocation was done with malloc

Aucun commentaire:

Enregistrer un commentaire