C++ 通过构造函数初始化列表调用的方法初始化 unordered_map 会抛出异常

问题描述 投票:0回答:1

我正在尝试在构造函数初始值设定项列表中调用的方法中填充 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。

c++ unordered-map
1个回答
0
投票

首先,这是我的两个想法。第一:

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()) {}
};

这使用委托构造函数技巧来本质上模拟构造函数初始值设定项列表中的局部变量。

© www.soinside.com 2019 - 2024. All rights reserved.