Efficient container for different derived classes in C ++

When programming games, I used to store all game objects in std :: vector with an initialized and fixed size. Recently, I felt the need for some inheritance among classes of game objects.

So let's say I have 40 classes derived from my Enemy class. If I want to store objects / instances of these classes in a vector, do I have the ability to save them as an Enemy * vector correctly? So the only thing that stands out adjacent is pointers, right? So I’ll still have a lot of cash misses if they need to be dereferenced, right?

Is there a “best practice” method for storing derived classes in contiguous allocated memory, so it takes a minimum amount of time to cycle them?

+5
source share
2 answers

Boost library just took it for this purpose: poly_collection. In particular, you are lookingbase_collection

Inside it uses several vectors, one per type (derived) type, while providing an interface close to standard containers.

, unique_ptr. : -, , , -, , -.

+3

?

struct alignas(...) Base {};
struct Derived1 : Base {};
struct Derived2 : Base {};

int main()
{
    std::vector<Base> v(2);
    new (&v[0]) Derived1();
    new (&v[1]) Derived2();
    return 0;
}

. . alignas , . ... ( 2), Derived1 Derived2 . sizeof(Derived1) 16, sizeof(Derived2) 24, alignas(32).

EDIT

@KubaOber, alignas , . - std::variant. :

int main()
{
    std::vector<std::variant<Derived1, Derived2>> v;
    v.emplace_back(Derived1());
    v.emplace_back(Derived2());

    for (const auto& e : v)
        std::visit(VisitPackage(), e);

    return 0;
}

VisitPackage :

struct VisitPackage
{
    void operator()(const Derived1&) { std::cout << "Derived 1.\n"; }
    void operator()(const Derived2&) { std::cout << "Derived 2.\n"; }
};
0

Source: https://habr.com/ru/post/1680991/


All Articles