diff --git a/include/CLI/Option.hpp b/include/CLI/Option.hpp index deb1f3e31..5be2667d5 100644 --- a/include/CLI/Option.hpp +++ b/include/CLI/Option.hpp @@ -319,7 +319,7 @@ class Option : public OptionBase { /// complete Results of parsing results_t results_{}; /// results after reduction - results_t proc_results_{}; + mutable results_t proc_results_{}; /// enumeration for the option state machine enum class option_state : char { parsing = 0, //!< The option is currently collecting parsed results @@ -700,7 +700,9 @@ class Option : public OptionBase { } else { res = reduced_results(); } - retval = detail::lexical_conversion(res, output); + // store the results in a stable location if the output is a view + proc_results_ = std::move(res); + retval = detail::lexical_conversion(proc_results_, output); } if(!retval) { throw ConversionError(get_name(), results_); diff --git a/tests/OptionTypeTest.cpp b/tests/OptionTypeTest.cpp index 8ea57262d..432d90f1b 100644 --- a/tests/OptionTypeTest.cpp +++ b/tests/OptionTypeTest.cpp @@ -385,6 +385,40 @@ TEST_CASE_METHOD(TApp, "stringLikeTests", "[optiontype]") { CHECK("bca" == m_type.m_value); } +#if CLI11_HAS_FILESYSTEM +#include +// test code from https://github.com/CLIUtils/CLI11/issues/881 +// https://github.com/Jean1995 +TEST_CASE_METHOD(TApp, "AsStringView", "[app]") { + app.add_option("--input", "input option")->default_val("optA")->check(CLI::IsMember({"optA", "optB", "optC"})); + + args = {}; + run(); + auto inputStr = app["--input"]->as(); + CHECK(inputStr == "optA"); + + args = {"--input", "optC"}; + run(); + inputStr = app["--input"]->as(); + CHECK(inputStr == "optC"); +} + +#endif + +TEST_CASE_METHOD(TApp, "AsStringRef", "[app]") { + app.add_option("--input", "input option")->default_val("optA")->check(CLI::IsMember({"optA", "optB", "optC"})); + + args = {}; + run(); + const std::string &inputStr = app["--input"]->as(); + CHECK(inputStr == "optA"); + + args = {"--input", "optC"}; + run(); + const std::string &inputStr2 = app["--input"]->as(); + CHECK(inputStr2 == "optC"); +} + TEST_CASE_METHOD(TApp, "VectorExpectedRange", "[optiontype]") { std::vector strvec;