Fix GrpcCodegen initialization

Initializing GrpcCodegen as a global static variable
is problematic because it is possible for it to get
destructed before the last instance of `GrpcLibraryCodegen`
gets destructed and leaves the program dealing with
a dangling pointer (imagine a scenario where another
thread is using gRPC resources and the main thread
tries to join it in an object's destructor after
main ends and CoreCodegen is destructed.)

In fact, Google style guide explicitly forbids
non-trivially-destructible global variables of static
storage duration for this and other reasons and the
solution in this commit is among the recommended
workarounds referenced in
https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
pull/17691/head
Mehrdad Afshari 6 years ago
parent 2ef35fe9db
commit b12dd1be05
  1. 9
      include/grpcpp/impl/grpc_library.h

@ -35,18 +35,17 @@ class GrpcLibrary final : public GrpcLibraryInterface {
void shutdown() override { grpc_shutdown(); }
};
static GrpcLibrary g_gli;
static CoreCodegen g_core_codegen;
/// Instantiating this class ensures the proper initialization of gRPC.
class GrpcLibraryInitializer final {
public:
GrpcLibraryInitializer() {
if (grpc::g_glip == nullptr) {
grpc::g_glip = &g_gli;
static auto* const g_gli = new GrpcLibrary();
grpc::g_glip = g_gli;
}
if (grpc::g_core_codegen_interface == nullptr) {
grpc::g_core_codegen_interface = &g_core_codegen;
static auto* const g_core_codegen = new CoreCodegen();
grpc::g_core_codegen_interface = g_core_codegen;
}
}

Loading…
Cancel
Save