I'm trying to create a hiearchy of classes in which parts are optional. I would like things to automatically be created as soon as variables are set.
For that I use C++17 std::optional feature.
Now in the example below I forgot to set the "parent" (test2_inst) first, yet g++, clang and msvc all compile and run fine altough with the "not set" output.
My questions now are: am I indeed doing the wrong thing in this example? and what would the proper way of resolving this? Or are the compilers doing the wrong thing?
#include <optional> class test1 { public: class test2 { public: int a, b; class test3 { public: int c, d; }; test3 test3_inst; }; std::optional<test2> test2_inst; }; int main(int argc, char *argv[]) { test1 *test1_inst = new test1(); // can set value test1_inst->test2_inst->test3_inst.c = 3; // yet optional says it is note set? if (test1_inst->test2_inst.has_value()) printf("set\n"); else printf("not set\n"); return 0; }
std::terminatecallsstd::abortwhich is considered a crash. It is well defined that if you don't catch an exception thenstd::terminatewill be called, so C++ some things are warranted to crash your program.