0

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?

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68
  • Don't know about nlohmann's jason implementation. But to begin with, it probably performs copy on data from "key" during the assignment. Generally, classes in C++ need to manage their resources on their own without user's interaction. I highly doubt that such a popular library has bugs in this regard. – ALX23z Apr 14 '21 at 15:30

1 Answers1

1

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.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Is this true even if the structure of previous value and new value completely different? Each key has a two level subkeys internally – Sreeraj Chundayil Apr 14 '21 at 16:01
  • 1
    @InQusitive Yes, the `json` object you assign to will be responsible for freeing it's own internal allocations and there is no manual memory management anywhere inside nlohmann/json so leaks are highly unlikely. There is only one place in the library where a `unique_ptr` `release()`s its internal pointer - but it looks really well guarded. – Ted Lyngmo Apr 14 '21 at 16:10