问题请教
std::vectorrapidjson::Value a; for(int i = 0; i < 100; i++) { rapidjson::Document doc; doc.SetObject(); doc.AddMember("0", i, doc.GetAllocator()); rapidjson::Value value; value.CopyFrom(doc, doc.GetAllocator()); a.push_back(std::move(value)); } 上述代码最终a数组中所有的rapidjson::Value都是相同的,而且都是最后一个添加到数组的Value,这是什么原因
That's an api miss-use. Your Document is destroyed after each iteration same as its allocator with allocated values.
Resulting std::vector contains invalid Values with dangling reference to de-allocated memory.
Consider to use std::vector<rapidjson::Document> (where each document is a single value) if you need individual allocators or use rapidjson::Document with array type.
Another approach is to use allocator directly, like this:
struct MyArray {
rapidjson::MemoryPoolAllocator<> allocator;
std::vector<rapidjson::Value> items;
};
MyArray a;
for(int i = 0; i < 100; i++) {
rapidjson::Value value(rapidjson::kObjectType);
value.AddMember("0", i, a.allocator);
a.items.push_back(std::move(value));
}
for (auto &value : a.items) {
std::cout << value["0"].GetInt() << ' ';
}
I recommend you to use rapidjson::Document array.
I think it's preferred way to just store array of values:
rapidjson::Document array(rapidjson::kArrayType);
array.PushBack(..., array.GetAllocator());