1

I need a string field in a Protobuf message to use a custom allocator for its internal char* buffer, instead of the default global allocator.

I am aware that google::protobuf::Arena will allocate the std::string object itself in the arena, but this does not affect the allocator used for that string's internal data buffer.

Ideally, I'd like the field to be a std::basic_string<..., MyCustomAllocator>. The [ctype] option seems limited to CORD and STRING_PIECE and doesn't appear to support arbitrary types.

Is there any way to control the allocator for a string field?

I am also considering using std::string_view. The idea is to define string_view field in my .proto and then manage the memory for the string buffer myself, outside of Protobuf. Do you see any pitfalls with this approach?

1
  • There is no built-in way to control the allocator for a string field's internal buffer in protobuf. If allocator control is critical, you may need to manage the memory outside of protobuf and use bytes or a custom wrapper. Commented Jun 9 at 8:22

1 Answer 1

0

The solution for me was to upgrade protobuf and use absl::string_view instead of std::string in my proto messages.

// message.proto
edition = "2023";

import "google/protobuf/cpp_features.proto";
option features.(pb.cpp).string_type=VIEW;
// Now each string field will be string_view in generated code.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.