可用于许多对象的 c++ 全局映射

标签 c++ swig

我有一个类需要能够在全局 STL 映射对象中查找值。但是,我不希望每个类都有一个拷贝,因为全局对象非常大。我目前的实现是这样的:

#include obj.h
#include init.h
map <string, vector<float> > gMap;
main() {int argc, char* argv[1]) {
  gMap = init(); // function in init.h that simply creates a map and returns it
  MyObj (); 
}

在obj.h中,有一个extern to gMap。

我很好奇是否有更好的方法来完成我在这里想要做的事情。想法?

我还计划通过 SWIG 将其导出到 Python,这在当前情况下会出现一些问题(这是重新考虑这一点的一些动机)。因此,如果任何解决方案都足够简单,可以在 SWIG 中解决最少的问题,那就太好了。

谢谢!

最佳答案

最好的替代方案可能是将巨型 map 存储在 std::shared_ptr(或 boost::shared_ptr)中,然后将它作为参数或成员传递给任何需要它的东西。

#include obj.h
#include init.h
#include <memory>
main() {int argc, char* argv[1]) {
  std::shared_ptr<map <string, vector<float> >> gMap; = init(); // function in init.h that simply creates a map and returns it
  MyObj f(gMap); 
}

另一种解决方案是通过引用将其传递给任何需要它的东西。然而,成员引用可能会很烦人。

关于可用于许多对象的 c++ 全局映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10746906/

相关文章:

c++ - 求 `hires_time_in_seconds()`的C++实现

c++ - CMAKE Compile_Flag

c++ - 在 std::bitset::operator[] 中创建的 std::bitset::reference 对象的生命周期?

c# - 将 boost::signal 包装到 C# 委托(delegate)

c++ - 新手 C++;添加 char* 数组?

c++ - 为了实现 5 个并发连接的高性能低级 Linux TCP/IP 套接字客户端,我必须采取哪些可能的选择?

php - 强制类型 SWIG

python - 从 C char* 到 python 字符串的 SWIG 类型映射

c# - swig + 单声道 : C# example errors of not finding the library

c# - 在 C# 中包装包含固定大小 C 数组的结构