c++ - 替换值时谁会删除以前的 nlohmann json 对象资源?
问题描述
我有一个键,我想用另一个 json 对象更改键的值。
json newjs = ...;
json tempjs = ...;
newjs["key"] = tempjs["key"];
以前存在的数据会发生什么变化newjs["key"]
?
nlohmann 类会自动销毁它还是内存泄漏?
或者我是否需要先手动擦除密钥并按上述方式分配?
解决方案
在内部,它由一个“ ordered_map
:一个保留插入顺序的最小的类似地图的容器”保存。
这里使用的实际标准容器ordered_map
是 a std::vector<std::pair<const Key, T>, Allocator>
,您所做的分配是通过
T& operator[](const Key& key)
{
return emplace(key, T{}).first->second;
}
其中emplace
定义为:
std::pair<iterator, bool> emplace(const key_type& key, T&& t)
{
for (auto it = this->begin(); it != this->end(); ++it)
{
if (it->first == key)
{
return {it, false};
}
}
Container::emplace_back(key, t);
return {--this->end(), true};
}
这意味着operator[]
尝试将emplace
默认初始化T
到内部映射中。如果key
地图中不存在,它将成功,否则将失败。
无论如何,当emplace
返回时,地图中将有一个,它是对返回T
的引用的引用,然后您将其复制分配到。T
operator[]
这是一个“正常”的复制分配,不应该发生泄漏。
推荐阅读
- ios - iOS 应用在 App Store 上显示的语言比在 Xcode 上更多
- kotlin - 如何在 Kotlin 中使用 volley 将标题放在 url 中?
- amazon-web-services - AWS - 在现有 VPC 中创建公有子网
- python - 对 python 装饰器感到困惑
- jquery - 背景过渡添加类
- c++ - 使用 IP Helper 的 Windows 中活动 UDP 连接的远程地址
- java - 当两个打开并具有相同名称时如何处理一个 JFrame
- css - 控制高度和边框底部flex子的方法
- csv - 导入、导出 TSV Laravel
- c++ - 如何在 C++ 中使用 NULL(或 0)初始化静态字符数组