Search code examples
c++protocol-buffers

Protocol Buffers SerializeToString/SerializeAsString memory management in C++


I want to serialize my protocol buffer messages in C++ to send them over HTTP. For this I can use SerializeAsString or SerializeToString. The following snippet illustrates my situation:

{
  shared_ptr<MyProtoBufObject> myProtoBufObject = getMyProtoBufObject();
  // serialize with SerializeToString
  string serialized1;
  myProtoBufObject.SerializeToString(&serialized1);
  // serialize with SerializeAsString
  string serialized2 = myProtoBufObject.SerializeAsString();

  // if myProtoBufObject has use_count = 1 it's memory will be released automatically.
  // But what should I do with serialized1 and serialized2?
}

My question is: What should I do with serialized1 and serialized2 regarding memory management? Will the memory be released after they go out of scope? If the memory is released after they go out of scope, why is that? My first guess is that since both are local variables, if both go out of scope, their destructors will be called. Similar to this:

{
  string s = "Hello";
}

However, I am not sure how that works if I pass a pointer (SerializeToString) or get it as return value (SerializeAsString). I'd be really grateful if someone could explain this.

The documentation doesn't provide any information on how that is handled. I am very new to C++ so it may be obvious to experienced developers.


Solution

  • The documentation could be more explicit, but SerializeToString's docstring states that it stores the serialization into the given string, which I'm pretty confident means the caller owns it.

    Similarly, SerializeAsString returns a std::string by value, which is the caller's to do as it likes.

    You can see in the code examples for the Message API that there is no memory management on the string that it used as the destination for serialization, they just let it go out of scope when done.