gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:36:30 27 4
gpt4 key购买 nike

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com