首页 > 解决方案 > 替换值时谁会删除以前的 nlohmann json 对象资源?

问题描述

我有一个键,我想用另一个 json 对象更改键的值。

   json newjs = ...;
   json tempjs = ...;
   newjs["key"] = tempjs["key"];

以前存在的数据会发生什么变化newjs["key"]

nlohmann 类会自动销毁它还是内存泄漏?

或者我是否需要先手动擦除密钥并按上述方式分配?

标签: c++jsonmemory-leaksnlohmann-json

解决方案


在内部,它由一个“ 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的引用的引用,然后您将其复制分配到。Toperator[]

这是一个“正常”的复制分配,不应该发生泄漏。


推荐阅读