1

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.

4
  • It's not obvious at all. If the documentation doesn't give you hints, check the implementation. If any of the two objects (or, rather serialized1, who's address you took) is still referenced somewhere inside, you can't return from that function without leaving it a dangling pointer. Commented Sep 24, 2021 at 6:05
  • @UlrichEckhardt Wouldn't SerializeAsString be a similar to this stackoverflow.com/a/3976954/465260 ? So in the case of SerializeAsString I don't have to worry about memory I suppose. For SerializeToString I have to check out the generated code. Commented Sep 24, 2021 at 6:29
  • 1
    Yep, that's right. Commented Sep 24, 2021 at 14:52
  • I have the exactly same question here! Commented Mar 18, 2022 at 13:45

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.