【发布时间】:2020-05-03 12:30:23
【问题描述】:
考虑一下这个 MCVE:
#include <boost/program_options.hpp>
#include <iostream>
#include <map>
namespace po = boost::program_options;
using namespace std;
po::options_description createOptions(const std::string& description, const map<string, string>& opts) {
po::options_description newoptions(description);
for (const auto& [k, v] : opts) {
newoptions.add_options()(k, v);
}
return newoptions;
}
int main() {
map<string, string> descMap = {
{ "key", "description" },
{ "hello", "world" }
};
auto opts = createOptions("My options", descMap);
cout << opts << endl;
}
我正在尝试编写一个便利函数,以在将类似选项插入options_description 对象时减少 C&P 代码的数量(原始代码使用通知程序,为简单起见已删除,但添加了更多样板文件)。
令我惊讶的是,there is no options_description_easy_init::operator() overload that accepts std::string,因此以 fails to compile 为例。
虽然我可以通过在 for 循环中对 k 和 v 调用 .c_str() 来轻松地使示例工作,当然是 this would be dangerous。为什么 boost 开发者遗漏了如此重要的过载?他们为什么不首先使用const std::string& 作为参数?
如果没有.c_str(),我怎样才能使这段代码工作?没有迹象表明指针内存将在内部复制(无论如何这会很奇怪),我真的不想回到过去并自己管理内存:-)
【问题讨论】:
-
您可以拨打
c_str()使其工作,不会有危险。参数为const char*,这意味着使用此参数调用的函数不拥有指向的内存,因此必须在函数返回后将其复制以进行进一步处理。如果参数为const std::string&,则会调用相同类型的副本
标签: c++ boost c++17 boost-program-options c-str