ARTICLE AD BOX
Use composition over inheritance:
struct Data {}; struct E { Data& data; E(Data& data) : data(data) {} }; struct A : public E {}; struct B : public E {}; struct EE { Data data; A x{data}; B y{data}; E& a() { return x; } E& b() { return y; } };The question you ask is actually unclear. You say you store references to E in a vector, but who owns the orginal EE instances where you got the references from? Create them on the stack or store them in a container. The references you get from a() and b() need not and should not be used to destroy the acutal instances:
{ std::vector<EE> ee; { std::vector<std::reference_wrapper<E>> refs; // do something with refs } } // EE objects are destroyedIf you need the return values of a() and b() to participate in ownership, make them smart pointers. However, it does not seem to be necessary.
In terms of your added main:
int main() { std::vector<EE> v; std::vector<E*> vec; for (size_t i = 0; i < 10; ++i) { v.push_back({}); vec.push_back(&(v.back().x)); vec.push_back(&(v.back().y)); } // shuffle the `vec` for (size_t i = 0; i < 20; ++i) { // your code goes here } } // At this point v and all its elements are destroyedI used a vector of pointers to E because its simpler. With reference wrappers its basically the same.
