I have a number of inheritance-related types that I want to use from standard container (std::reference_wrapper is a proper value type for such a container, AFAIU). However, I do not understand, how to initialize such a container when the values, the references to which are inserted in a map, are not global variables. E.g.:
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
struct I
{
virtual void print() = 0;
};
struct S1: public I
{
void print() override
{
cout << "S1 " << i << endl;
}
int i{};
};
struct S2: public I
{
void print() override
{
cout << "S2 " << f << endl;
}
float f{};
};
std::vector<reference_wrapper<I>> v;
void init()
{
S1 x{};
S2 y{};
v.emplace_back(x);
v.emplace_back(y);
}
int main()
{
init();
v[1].get().print();
return 0;
}
This compiles, but I get some memory corruption at run-time. What is a proper way of initializing container of std::reference_wrappers?
vto own the instances you store within, you need it to be anstd::vector<std::unique_ptr<I>>and use dynamic allocation throughstd::make_unique<I>().