jbeder / yaml-cpp

A YAML parser and emitter in C++
MIT License
5.05k stars 1.81k forks source link

Copy constructor and assignment does not obey constness of the parameter #391

Open hjanetzek opened 8 years ago

hjanetzek commented 8 years ago

This leads to hard to track down bugs when using Node in cases where the correct copy-behavior is required.

One way to have Nodes at least work correctly with stl vector is to implement move constructor and assignment which are then used in favor of copy versions.

https://github.com/jbeder/yaml-cpp/pull/390

misuo commented 7 years ago

I believe I've hit this problem as well. Have a std::vector of elements containing YAML::Node that is sorted using std::sort - requires proper copy assignment inclusive on the YAML::Node member.

hansfn commented 3 years ago

Today, I tried exactly that - sorting a std::vector of elements containing YAML::Node

std::vector<YAML::Node> nodes;
nodes.pushback(...);

std::sort(nodes.begin(), nodes.end(),
   [](const YAML::Node& nodeA, const YAML::Node& nodeB) { 
           return nodeA["id"].as<int>() < nodeB["id"].as<int>();});

YAML::Node writeNode;
int i = 0;
for (auto node : nodes) {
   writeNode["Topic0" + std::to_string(++i)] = node;
}

The resulting YAML file after saving writeNode was very interesting with anchors "&1" and references "*1" to avoid repeating duplicate nodes. At least I learned something new about YAML.

Anyway, is there a work-around? We are using yaml-cpp 0.6.3.