Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reflex_object.cpp中的静态变量sg_obj_map初始化顺序的不确定性导致崩溃 #190

Open
fan-chao opened this issue Sep 19, 2023 · 0 comments

Comments

@fan-chao
Copy link

由于IMPLEMENT_REFLEX_OBJECT_EX使用时所在的编译单元与reflex_object.cpp不同,如kafkahandler_default.cpp,那么kafkahandler_default.cpp中的静态变量static cnstream::ClassInfo sclass_info的初始化与reflex_object.cpp中的全局静态变量static std::map<std::string, ClassInfo> sg_obj_map的初始化顺序是不确定的。

如果kafkahandler_default.cpp中的sclass_info初始化早于reflex_object.cpp中的sg_obj_map,那么sclass_info在调用ReflexObject::Register函数时候, obj_map.insert(std::pair<std::string, ClassInfo>(info.name(), info));
这一行就会导致崩溃,原因是此时sg_obj_map并没有初始化。

其中一个解决方案是,使用函数返回静态局部变量的方式来创建单例。例如:

std::map<std::string, ClassInfo<ReflexObject>>& GetMap() {
    static std::map<std::string, ClassInfo<ReflexObject>> sg_obj_map;
    return sg_obj_map;
}

然后你可以通过调用GetMap()函数来访问这个映射,即ReflexObject::Register这个函数改为:

bool ReflexObject::Register(const ClassInfo<ReflexObject>& info) {
  auto& obj_map = GetMap();
  if (obj_map.find(info.name()) != obj_map.end()) {
    LOGI(REFLEX_OBJECT) << "Register object named [" << info.name() << "] failed!!!"
                        << "Object name has been registered.";
    return false;
  }

  obj_map.insert(std::pair<std::string, ClassInfo<ReflexObject>>(info.name(), info));

  LOGI(REFLEX_OBJECT) << "Register object named [" << info.name() << "]";
  return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant