大佬教程收集整理的这篇文章主要介绍了c – 使用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() );
将字符串对象放在向量中(以防止它们被破坏)也不起作用 – 因为字符串在放入向量时被复制,而原始字符串仍然被销毁:
// 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(),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(),args.size() );
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 *构建动态结构的更好方法?全部内容,希望文章能够帮你解决c – 使用char *构建动态结构的更好方法?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。