rapidjson icon indicating copy to clipboard operation
rapidjson copied to clipboard

问题请教

Open dakeleblack opened this issue 2 years ago • 2 comments

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,这是什么原因

dakeleblack avatar Nov 17 '23 09:11 dakeleblack

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() << ' ';
}

aikawayataro avatar Nov 18 '23 06:11 aikawayataro

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());

aikawayataro avatar Nov 18 '23 06:11 aikawayataro