2

When I'm running following code with yaml-cpp library:

YAML::Node node1 = YAML::Load("{ hello: [item1, item2] }");
YAML::Node node2 = node1;

node1 = node1["hello"];

std::cout << node2 << "\n";
std::cout << node1 << "\n";

I end up with same node contained in both node1 and node2 variables. It prints [item1, item2] in both cases. Is it the right behavior or something is messed up? I'm wondering how can I keep reference at original node? I use g++ 5.1.0 and boost 1.59.0 if it matters.

1 Answer 1

2

Nodes in yaml-cpp are reference types, not value types; but this isn't implemented consistently. See this issue on the project page, which highlights this question.

In your specific case, when you write

YAML::Node node2 = node1;

it makes these two references that refer to the same value; that is, anything you do to one be reflected in the other.

Then, when you write

node1 = node1["hello"];

it does two things: first, node1["hello"] pulls out the (reference to) the "hello" key in node, which is [item1, item2]. Next, it assigns this to node1.

This is where the API is somewhat inconsistently implemented. Since operator= is treated with reference semantics, this sets the value that node1 references as being replaced. Since node2 was an alias for node1, it, too, has its value replaced.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.