How can I keep a reference to something that gets moved?

Viewed 180

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.

1 Answers

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.

Related