开发者

Circumvent c++ null-terminated string frustration

开发者 https://www.devze.com 2022-12-26 05:33 出处:网络
I\'m using boost::program_options and it suffers from the same as many other c++ libs, even std itself: It still uses C-style null-terminated strings, because nobody really likes the weak std::string.

I'm using boost::program_options and it suffers from the same as many other c++ libs, even std itself: It still uses C-style null-terminated strings, because nobody really likes the weak std::string.

The method in question is:

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

The typical use case is just fine:

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

However, I need the name of the option to be set dynamically. The reason is that in some cases I nead a custom prefix, which is added to the string by my function std::string key(const std::string& k):

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

This fails.

I could now use c_str() on the 开发者_开发百科std::string but that's evil -- I don't know how long program_options keeps the variable around and if my string is still alive when needed.

I could also reserve memory in a buffer etc. and hand in that. The buffer is never freed and it sucks/is evil.

Is there anything else I can do to circumvent the C-style string mess in this situation?


It's pretty strong convention to not hold on to const char*'s beyond the life of a function call like this. As long as they're not bucking this convention, .c_str() is the expected and best way to do what you're trying to do IMO.

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


I agree with Will that it is unlikely that the parameter will be referenced beyond the function call. However, if you really think that is an issue, you could use a static string or char array to store the output of key() and pass that into the operator()(). Though, this might be the same as a single memory leak depending on your point of view.

0

精彩评论

暂无评论...
验证码 换一张
取 消