c++ - 使用 char* 构建动态结构的更好方法?

标签 c++ struct

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

相关文章:

android - 纠结谷歌测试

c - 轻松访问多个结构数组

ios - 我如何组织这些数据?

c++ - 如何填充结构 vector

swift - 从 struct init 中提取函数

iphone - 在类之间共享结构信息 - Objective C - OpenGL ES

c++ - 策略模式是否允许状态?

c++ - Qt将数据结构分成组

c++ - 有没有办法确保在 C++ 中传递的模板参数是一个迭代器?

C++ 对容器上迭代器行为的正式要求