yaml-cpp 比较的意外结果

Unexpected results for yaml-cpp comparisons

考虑以下代码 (yamltest.cpp):

#include <yaml-cpp/yaml.h>
#include <iostream>
#include <string>

int main() {
  std::string val = "[1, 2, 3]";
  YAML::Node yn0 = YAML::Load(val);
  YAML::Node yn1 = YAML::Load(val);

  std::cout << "===== yn0 =====\n" << yn0 << std::endl;
  std::cout << "\n"  << std::endl;
  std::cout << "===== yn1 =====\n\n" << yn1 << std::endl;

  std::cout << std::boolalpha;
  std::cout << "yn0 == yn0: " << (yn0==yn0) << std::endl;
  std::cout << "yn1 == yn1: " << (yn1==yn1) << std::endl;

  std::cout << "yn0 == yn1: " << (yn0==yn1) << std::endl;
  std::cout << "yn1 == yn0: " << (yn1==yn0) << std::endl;
  std::cout << "YAML::Load(val) == YAML::Load(val): " << (YAML::Load(val)==YAML::Load(val)) << "\n" << std::endl;

  std::cout << "yn0 != yn0: " << (yn0!=yn0) << std::endl;
  std::cout << "yn1 != yn1: " << (yn1!=yn1) << std::endl;

  std::cout << "yn0 != yn1: " << (yn0!=yn1) << std::endl;
  std::cout << "yn1 != yn0: " << (yn1!=yn0) << std::endl;
  std::cout << "YAML::Load(val) != YAML::Load(val): " << (YAML::Load(val)!=YAML::Load(val)) << std::endl;
  std::cout << std::noboolalpha;

  return 0;
}

及其关联的 Makefile:

yt:
    g++ -g -Wall yamltest.cpp -o yt -lyaml-cpp

clean:
    rm yt

运行 它产生以下结果:

$ ./yt 
===== yn0 =====
[1, 2, 3]


===== yn1 =====
[1, 2, 3]

yn0 == yn0: true
yn1 == yn1: true
yn0 == yn1: false
yn1 == yn0: false
YAML::Load(val) == YAML::Load(val): false

yn0 != yn0: false
yn1 != yn1: false
yn0 != yn1: false
yn1 != yn0: false
YAML::Load(val) != YAML::Load(val): false

我希望所有 == 测试达到 return true,所有 != 测试达到 return false,但是这显然没有发生。那么,这是比较 YAML-CPP 对象以测试等效性的正确方法吗?如果不是,正确的做法是什么?

这是 CentOS 7.x 和 GCC 9.2.0 上的 运行。

查看 the codeoperator== 正在测试身份而不是平等。

bool YAML::detail::node::is(const node& rhs) const { return m_pRef == rhs.m_pRef; }

因此,operator== 仅当对象相同而不是包含相同值时才 return 为真。

对于 operator!= 的情况,这是一个错误(恕我直言),节点是 implicitly converted to bool type,值为 unspecified_bool::true_value。因此,表达式总是错误的。

谷歌搜索了一下,有针对您的用例的开放增强请求和 some code contributed 比较等效性。