Search code examples
c++protocol-buffersproto

What is the lifetime of the descriptor of a generated protobuf message?


I am using Protobuf 2 in my project. I want to use DynamicMessageFactory to create messages at run-time. DynamicMessageFactoryrequires a Descriptor*. I am passing Descriptor* of a mutable message of a generated class. The documentation says that Descriptor must outlive DynamicMessageFactory which in turn should outlive the message generated by the factory.

What is the lifetime of the descriptor of a generated class? Is it static member of the class?


Solution

  • Descriptors for generated-code / compiled-in message classes live forever, so you should be good.

    But if your types are complied-in, then there's no reason to use DynamicMessageFactory. Dynamic messages are much slower than generated code, and generated code supports the whole dynamic interface in addition to the generated interface. You could use the generated factory instead to get instances of generated messages. Or, an even cleaner strategy is to get the message's prototype by calling MyType::default_instance(), and then pass around that pointer rather than passing around the descriptor.

    If you need to mix some dynamic types with some generated types, also consider using DynamicMessageFactory::SetDelegateToGeneratedFactory().