fantasy-peak / yaml_cpp_struct

It's easy to mapping yaml to cpp's struct
MIT License
25 stars 5 forks source link

Nested structure with std::optional types #5

Open requizm opened 2 months ago

requizm commented 2 months ago

It seems like gives an error when deserializing nested structs that have optional fields. Example:

struct Child
{
  std::optional<int32_t> age; // Error because couldn't find "age"
};

struct Parent
{
  Child child;
};
fantasy-peak commented 2 months ago

could you provide a complete example

fantasy-peak commented 2 months ago

https://github.com/fantasy-peak/yaml_cpp_struct/blob/9724ab3be8ccac787196036ebcd24d55243eec7b/example/main.cpp#L174

requizm commented 2 months ago

I'm using v1.0.2 via xmake.

main.cpp:

#include <optional>

#include <yaml_cpp_struct.hpp>

struct Settings
{
  int32_t port;
  std::optional<int32_t> thread_count;
};
YCS_ADD_STRUCT(Settings, port, thread_count);

struct Config
{
  Settings settings;
};
YCS_ADD_STRUCT(Config, settings);

int main(int argc, char **argv)
{
  auto [config_opt, error] = yaml_cpp_struct::from_yaml<Config>("./config.yaml");
}

config.yaml

settings:
    port: 5555

Error:

Exception thrown at 0x00007FFA5FEAAB89 in yaml_cpp_struct_optional_test.exe: Microsoft C++ exception: YAML::InvalidNode at memory location 0x00000091A25DEC90.

Debugging status before throwing exception: image

fantasy-peak commented 2 months ago

This exception seems to be thrown by yaml cpp,I don't have the Windows development environment at hand. I checked with memory tools on Linux and didn't find any problems. I need to study it carefully

fantasy-peak commented 2 months ago
---
settings:
  port: 50

[9:49:06] root:bin git:(main*) # xmake build -v -y  
[100%]: build ok, spent 0.021s
warning: You are working in the project directory(/root/github/yaml_cpp_struct/example) and you can also
force to build in current directory via run `xmake -P .`
[9:49:08] root:bin git:(main*) # xmake install -o . 
installing example ..
installing example to . ..
install ok!
[9:49:10] root:bin git:(main*) # valgrind --log-file=a.txt --tool=memcheck --leak-check=full -s  --track-origins=yes ././example ../config.yaml
50
-1
[9:49:13] root:bin git:(main*) # cat a.txt
==105428== Memcheck, a memory error detector
==105428== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==105428== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==105428== Command: ././example ../config.yaml
==105428== Parent PID: 99174
==105428== 
==105428== 
==105428== HEAP SUMMARY:
==105428==     in use at exit: 0 bytes in 0 blocks
==105428==   total heap usage: 359 allocs, 359 frees, 113,936 bytes allocated
==105428== 
==105428== All heap blocks were freed -- no leaks are possible
==105428== 
==105428== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
fantasy-peak commented 2 months ago

could you use test branch for test ? https://github.com/fantasy-peak/yaml_cpp_struct/tree/test