From b12dd1be055d81a68d535cc052aac804734453df Mon Sep 17 00:00:00 2001 From: Mehrdad Afshari Date: Thu, 10 Jan 2019 22:12:03 -0800 Subject: [PATCH] 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 --- include/grpcpp/impl/grpc_library.h | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/include/grpcpp/impl/grpc_library.h b/include/grpcpp/impl/grpc_library.h index d1f3ff1297b..3711c098790 100644 --- a/include/grpcpp/impl/grpc_library.h +++ b/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; } }