c++yaml-cpp

Yaml-cpp emits an doublequoted yaml string when emitted in an destructor


I‘m trying to serialize some data using yaml-cpp on destruction of an object. This normally works fine but as soon as that object is static something weird happens: Every string, also keys of maps, is wrapped in double quotes. Example

struct EmitterTest
{
    ~EmitterTest()
    {
        Serialize();
    }

    void Serialize()
    {
        YAML::Emitter out;

        out << YAML::BeginMap << YAML::Key << "Test";
        out << YAML::BeginMap;
        out << YAML::Key << "String1" << YAML::Value << "String1";
        out << YAML::Key << "String2" << YAML::Value << "String2";
        out << YAML::Key << "String3" << YAML::Value << "Foo";
        out << YAML::EndMap;
        out << YAML::EndMap;

        std::cout << out.c_str() << std::endl;
    }
}

static EmitterTest s_Test;

int main()
{
    s_Test.Serialize();
}

Expected output:

Test:
  String1: String1
  String2: String2
  String3: Foo
Test:
  String1: String1
  String2: String2
  String3: Foo

Actual output:

Test:
  String1: String1
  String2: String2
  String3: Foo
"Test":
  "String1": "String1"
  "String2": "String2"
  "String3": "Foo"

Note that this behavior only occurs when the Serialize() function is called once before destruction.


Solution

  • The solution to this is not emitting in an destructor, where you don't know when its beeing destructed like a static variable.