我正在尝试在构造函数初始值设定项列表中调用的方法中填充 unordered_map [类成员]。我在
map[0] = 1
处收到运行时异常,这似乎是由于在调用方法之前未构造成员。 (我在 unordered_map 构造函数上放置了一个断点,但没有命中)。有没有办法在调用方法之前强制构造 unordered_map 成员?
#include <iostream>
#include <unordered_map>
class Base
{
public:
Base(int chan) { }
};
class Foo : public Base
{
std::unordered_map<int, int> map;
int Init(int chan)
{
// fill map
map[0] = 1;
map[1] = 3;
return map[chan];
}
public:
Foo(int chan) : Base(Init(chan)) { }
};
int main()
{
Foo foo(0);
}
使用 Visual Studio 2019。
首先,这是我的两个想法。第一:
struct MapWrapper {
std::unordered_map<int, int> map;
};
class Foo : private MapWrapper, public Base {
/* The rest of the class can remain unchanged, except that
there's no `map` member; it's inherited from MapWrapper */
};
这会强制
map
在 Base
之前构建。
第二:
class Foo : public Base
{
std::unordered_map<int, int> map;
static std::unordered_map<int, int> MakeMap() {
std::unordered_map<int, int> map;
map[0] = 1;
map[1] = 3;
return map;
}
Foo(int chan, std::unordered_map<int, int>&& temp_map)
: Base(temp_map[chan]), map(std::move(temp_map)) {}
public:
Foo(int chan) : Foo(chan, MakeMap()) {}
};
这使用委托构造函数技巧来本质上模拟构造函数初始值设定项列表中的局部变量。