我想使用类似于XPath的语言生成一个QJsonDocument。例如,给出一组参数:
"#/node1/node2/val"
"hello"应该会产生:
{
"node1":{
"node2":{
"val": "hello"
}
}
}我的实现如下所示:
QJsonDocument doc;
const auto ascending_construct = [&](const QString& json_pointer, QJsonValue val){
auto components = json_pointer.split("/");
//TODO: sanity check components
auto inner = new QJsonObject {{components[components.size()-1], val}};
auto current = inner;
for(int i = components.size() - 2; i >= 1; i--){
auto parent = new QJsonObject{{components[i], std::move(*current)}};
current = parent;
}
return current;
};
QJsonObject root(std::move(*ascending_construct(json_pointer, value)));但是valgrind告诉我有一个内存泄漏。我知道我是在堆上构造QJsonObject,但我认为取消对它们的引用然后移动它们会将所有权“转移”给parent,当最上层的父对象被销毁时,它应该向下传播销毁。
如何修复此内存泄漏?
发布于 2021-06-23 16:32:37
std::move将被引用的对象“挖空”,但不会自动delete它,因此您确实是在泄漏内存。幸运的是,这不是必需的,因为QJsonObjects是隐式共享的。所以:
const auto ascending_construct = [&](const QString& json_pointer, QJsonValue val){
auto components = json_pointer.split("/");
//TODO: sanity check components
auto current = val;
while (!components.isEmpty()) {
current = QJsonObject{{components.takeLast(), current}};
}
return current;
};
QJsonObject root = ascending_construct(json_pointer, value);https://stackoverflow.com/questions/68095945
复制相似问题