c++ - 规避 C++ 空终止字符串的挫败感

标签 c++ string

我正在使用 boost::program_options,它与许多其他 C++ 库一样受到同样的困扰,甚至是 std 本身:它仍然使用 C 风格的空终止字符串,因为没有人真正喜欢弱 std::字符串.

有问题的方法是:

options_description_easy_init&
operator()(const char* name,
           const value_semantic* s,
           const char* description);

典型用例就好了:

options.add_options()
    ("graphical", bool_switch(&isGraphical)->default_value(false),
     "Show any graphical output during runtime")

但是,我需要动态设置选项的名称。原因是在某些情况下我需要一个自定义前缀,它由我的函数添加到字符串 std::string key(const std::string& k):

options.add_options()
    (key("graphical"), bool_switch(&isGraphical)->default_value(false),
     "Show any graphical output during runtime")

这失败了。

我现在可以在 std::string 上使用 c_str() 但这很糟糕——我不知道 program_options 将变量保留多长时间以及我的字符串在需要时是否仍然存在。

我也可以在缓冲区等中保留内存并提交。缓冲区永远不会被释放,它很糟糕/很邪恶。

在这种情况下,我还能做些什么来避免 C 风格的字符串困惑?

最佳答案

在像这样的函数调用的生命周期之外不保留 const char* 是非常严格的约定。只要他们不违背这一惯例,.c_str() 就是执行您正在尝试执行的 IMO 的预期和最佳方法。

options.add_options()
    (key("graphical").c_str(), bool_switch(&isGraphical)->default_value(false),
     "Show any graphical output during runtime")

关于c++ - 规避 C++ 空终止字符串的挫败感,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2596500/

相关文章:

Python:如何删除字符串中不相邻的重复单词?

c++ - 在 Netbeans 项目中包含 C++ 库源?

c++ - 结合 A* 寻路和点击移动

string - 在字符串中查找特定数字?

c++ - 是否有打印可选值的约定?

python 类型错误

c++ - 假设我不使用任何重载函数,有没有办法可以停止所有名称修改?

c++ - Boost spirit 将整数解析为自定义列表模板

c++ - 并行 for_each 比 std::for_each 慢两倍以上

android - 根据用户偏好加载资源