How to create a node where key is a dynamic string?
Closed this issue · 2 comments
I want to generate node with dynamic string as key, such as:
std::string key = "my_key";
node[ryml::to_csubstr(key)] << 1;
It is compilable but the key is assumed as a static string anyway and the variable key must be kept all the time.
The only solution I can think of is to new std::string to heap and leave it there, but that will cause obvious memory leak.
Is there proper way in the library design?
You either keep the string around or serialize to the tree's arena. To achieve the latter using the node API, use a combination of operator<<
and the disambiguation function ryml::key()
(otherwise, it would serialize the string as a val). See the relevant example in the quickstart.
In your case:
std::string k = "mykey";
node << ryml::key(k); // serialize the key to the arena
node << 1; // serialize the value to the arena
or quite simply:
node << ryml::key(key) << 1;
Internally, operator<<(ryml::key(k))
will call tree.copy_to_arena()
.
You can also do it directly yourself. This sample has the same effect as above:
ryml::csubstr key_copy = node.tree()->copy_to_arena(key);
node[key_copy] << 1;
perfect! thank you!