我想使用 C++ 中的 C 风格 API,它采用可变数量的结构和 char* 成员,如下所示:
typedef struct _FOO
{
const char * name;
const char * value;
} FOO;
void ApiFunc(FOO const* args, unsigned count);
为了填充参数,我需要循环一些其他数据并即时创建 FOO 条目。最优雅的方法是什么?
以下方法乍一看似乎很简单,但并不奏效(因为字符串实例超出范围并在调用 ApiFunc() 之前被销毁):
// Approach A: this does *not* work
std::vector<FOO> args;
for (...)
{
string name = ... // something which gets
string value = ... // calculated in the loop
args.push_back( FOO{name.c_str(), value.c_str()} );
}
ApiFunc( args.data(), args.size() );
将字符串对象放入 vector 中(以防止它们被破坏)也不起作用 - 因为字符串在放入 vector 时被复制,并且原始字符串仍然被破坏:
// Approach B: this also does *not* work
std::vector<string> strings;
for (...)
{
string name = ... // something which gets
string value = ... // calculated in the loop
strings.push_back( name );
strings.push_back( value );
args.push_back( FOO{name.c_str(), value.c_str()} );
}
ApiFunc( args.data(), args.size() );
我可以通过在堆上创建字符串对象并使用 auto_ptr 来跟踪它们来防止这种情况发生,但是有更好的方法吗?
// Approach C: this does work
std::vector<auto_ptr<string>> strings;
for (...)
{
string* name = new ...
string* value = new ...
strings.push_back( auto_ptr<string>(name) );
strings.push_back( value );
args.push_back( FOO{name.c_str(), value.c_str()} );
}
ApiFunc( args.data(), args.size() );
虽然方法 C. 似乎可行,但我发现它相当不明显/难以理解。有什么改进建议吗?
最佳答案
我很确定 std::vector<auto_ptr<T>>
标准不允许。使用 unique_ptr
反而。或者,在 vector 中构建字符串,然后从中构建参数。
std::vector<std::pair<std::string, std::string>> strings;
for (...)
{
const std::string name = ...;
const std::string value = ...;
strings.push_back( std::make_pair( name, value ) );
}
// Note: This loop must be separate so that 'strings' will not reallocate and potentially
// invalidate the pointers returned by elements in it.
for (const auto& pair : strings)
{
args.push_back( FOO{pair.first.c_str(), pair.second.c_str()} );
}
ApiFunc( args.data(), args.size() );
关于c++ - 使用 char* 构建动态结构的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34745574/