【发布时间】:2019-09-09 13:03:33
【问题描述】:
我有许多我想从标准容器中使用的继承相关类型(std::reference_wrapper 是此类容器的正确值类型,AFAIU)。但是,我不明白,当插入到映射中的引用值不是全局变量时,如何初始化这样的容器。例如:
#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;
}
这可以编译,但我在运行时遇到了一些内存损坏。初始化std::reference_wrappers的容器的正确方法是什么?
【问题讨论】:
-
如果您需要
v拥有您存储的实例,您需要它是std::vector<std::unique_ptr<I>>并通过std::make_unique<I>()使用动态分配。
标签: c++ polymorphism containers reference-wrapper