protocolbuffers / protocolbuffers/protocolbuffers.github.io

repeated_ptr_field.h -- document lifetime of pointers and references

Đang mở
#241 4 bình luận 0 reaction 1 người được giao Xem trên GitHub

@jguamie đang làm issue này rồi.

Từ ngày 17/10/2025.

Ngôn ngữ chính
HTML
Star
69
Fork
179
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

In STL containers that store value elements (e.g. vector<Bar> as opposed to vector<Bar*>), element pointers are invalidated by operations such as adding or removing elements from the container.

The generated C++ code for repeated message fields returns a container of value elements:
https://protobuf.dev/reference/cpp/cpp-generated/#repeatedmessage

const RepeatedPtrField<Bar>& bar()
RepeatedPtrField<Bar>* mutable_bar()

However, based on the "Ptr" in the name, and looking at the current implementation, it seems that the intention is for RepeatedPtrField to behave more like vector<Foo*>, where it is safe to hold on to pointers to the underlying messages.

For example, is this safe?:

message Bar {
  string baz = 1;
}
message Foo {
  repeated Bar bar = 1;
}
...

std::string do_something(Foo *foo) {
  // Get a reference to first element of bar
  const Bar& bar = *foo->bar()->begin();

  // Add a bar to foo
  foo->add_bar();

  // Do something with the first bar reference
  return bar.baz();
}

I'm not finding clear documentation on this behavior though. Assuming it is meant to be safe to hold on to these references/pointers, could this please be documented?

Related stack overflow making the same assumption:
https://stackoverflow.com/questions/33219022/do-pointers-to-items-of-a-repeated-gpb-field-stay-valid-if-the-field-is-modified

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.