Search code examples
c++jsonmemory-leaksnlohmann-json

Who deletes previous nlohmann json object resources when value is replaced?


I have a key and I want to change the value of the key with another json object.

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

What will happen to the data existed in newjs["key"] previously?

Will nlohmann class automatically destroy it or is it a memory leak?

OR do I need to manually erase the key first and assign as above?


Solution

  • Internally it's a kept by an "ordered_map: a minimal map-like container that preserves insertion order".

    The actual standard container used in this ordered_map is a std::vector<std::pair<const Key, T>, Allocator> and the assignment you do is performed via

        T& operator[](const Key& key)
        {
            return emplace(key, T{}).first->second;
        }
    

    where emplace is defined as:

        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};
        }
    

    This means that operator[] tries to emplace a default initialized T into the internal map. If key isn't present in the map, it will succeed, otherwise it will fail.

    Regardless of which, when emplace returns, there will be a T in the map and it's a reference to that T that is returned by operator[] and it's that you then copy assign to.

    It's a "normal" copy assignment and no leaks should happen.