让升压程序选项在函数作用域后持续存在

Getting boost program options to persist after function scope

我有一个函数接受 boost::program_options::options_description,添加一些选项,然后 returns 返回。似乎我的选项在函数范围结束后不再存在,并且我的选项消失了。我如何让他们坚持下去?

#include <boost/program_options.hpp>
#include <utility>


void generic_args(boost::program_options::options_description desc, boost::program_options::positional_options_description p) {
    desc.add_options()
        ("input", boost::program_options::value<std::vector<std::string>>(), "input files")
        ("help,h", "produce help message")
        ("verbose,v", "put the pretty words and numbers on the light screen");

    p.add("input", -1);
}

int main(int argc, const char** argv) {
    boost::program_options::options_description desc("Allowed options");
    boost::program_options::positional_options_description p;
    generic_args(desc, p);
    boost::program_options::variables_map parameters;
    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).positional(p).run(), parameters);
    boost::program_options::notify(parameters);
    return 0;
}

这是输出:

scott@beast:~/test/test_args$ g++ -std=c++11 main.cpp -o a.out -lboost_program_options
scott@beast:~/test/test_args$ ./a.out
scott@beast:~/test/test_args$ ./a.out --help
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::program_options::unknown_option> >'
  what():  unrecognised option '--help'
Aborted (core dumped)

您应该更改 generic_args 以通过引用获取参数:

void generic_args(boost::program_options::options_description &desc,
                  boost::program_options::positional_options_description &p)
{
  // ...
}

当前 generic_args 修改 descpcopy(它们按值传递)。

查看 Does C++ pass objects by value or reference? and What's the difference between passing by reference vs. passing by value? 了解更多详情。