6

I have something as the following using rapidjson

rapidjson::Value parent;
parent.SetObject();

rapidjson::Value child;
child.SetObject();

parent.AddMember("child", child, document.GetAllocator());

The problem is when I call parent.AddMember(), the library nullifies my child variable because rapidjson uses move semantics.

How can I still keep a reference to the child value when it gets moved?

Ideally, I'd like to keep a reference to the child node so that I can modify it later, without having to go find it in the JSON tree.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Lord Nikon
  • 172
  • 8
  • You could read books about garbage collection, e.g. https://gchandbook.org/ – Basile Starynkevitch Sep 01 '21 at 17:30
  • What does addmember return? I tried searching the documentation but couldn't find it – linuxfever Sep 01 '21 at 17:59
  • @linuxfever `*this` - that is, a reference to `parent` – Ted Lyngmo Sep 01 '21 at 18:14
  • Seems like what you want is not a reference to a `Value` but rather a reference to the Value's internal state (i.e. to whatever internal data-object it is that gets moved from one `Value` object to another as methods like `AddMember()` get called). Dunno if that's supported by the rapidjson API, though. – Jeremy Friesner Sep 01 '21 at 19:18

1 Answers1

0

Not specific to rapidjson:

When you have a reference to an object child, and the resource owned by child is transferred to another object by moving, the reference to child is still valid, but the referred object is no longer the one that owns the resource.

You cannot make the original reference variable to refer to the other object. But you could use a pointer or a reference wrapper instead, if you change the value of the pointer when the pointed object is moved.


I'm not familiar with rapidjson, but with a brief browsing of documentation, you could at least use parent.FindMember to get a reference to the newly created member, and update the pointer to that.

eerorika
  • 232,697
  • 12
  • 197
  • 326