repeated_ptr_field.h -- document lifetime of pointers and references
@jguamie 已经在做这个了。
开始于 2025年10月17日。
评估
这个 Issue 还没有评估数据。
描述
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
- 主要语言
- HTML
- 星标
- 69
- 派生
- 179
- PR 合并指标
- 30 天内没有已合并 PR
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
protocolbuffers/protocolbuffers.github.io 的其他 Issue
-
难度 2/5 1-3 小时 新手友好度 78/100
-
Protocol Buffers 未关闭
难度 5/5 一周以上 新手友好度 15/100
protocolbuffers/protocolbuffers.github.io#319 · 1 条评论 ·
-
难度 3/5 1-2 天 新手友好度 35/100
-
难度 4/5 3-5 天 新手友好度 25/100
-
难度 3/5 1-2 天 新手友好度 45/100