![](/img/trans.png)
[英]C++ Iterating over vector of class pointers and using base function
[英]C++: Iterating over a string vector and using the index for putenv
我有一個字符串向量,它是通過解析配置文件創建的。 所有字符串都應采用key=value
格式。 我想遍歷向量,並使用 putenv 函數將環境變量設置為鍵值對。
編碼:
for(auto it = settings.begin(); it != settings.end(); it++) {
try {
auto i = it - settings.begin();
cout << i << endl;
putenv(settings.at(i));
} catch (...) {
cout << "Config is not in the format key=value ... please correct" << endl;
}
}
這會引發錯誤:
cannot convert ‘__gnu_cxx::__alloc_traits<std::allocator<std::basic_string<char> > >::value_type {aka std::basic_string<char>}’ to ‘char*’ for argument ‘1’ to ‘int putenv(char*)’
我對 C++ 很陌生,所有這些變量類型和指針都讓我感到困惑。
你正在混合 C 和 C++ 的東西。
std::string
。putenv
是一個“舊”函數,它需要一個指向char
緩沖區的指針,即一個 C 字符串。 幸運的是, std::string
可以輕松獲得其中之一:
putenv(settings.at(i).c_str());
// ^^^^^^^^
但是,那里仍然存在問題。 putenv
獲取您提供的緩沖區的“所有權”,並希望它“永遠”持續。 你的不會; 它只會在std::string
被修改或銷毀之前存在。 還不夠好!
按照慣例,我們在這里使用 C 的strdup
來分配char
緩沖區的副本。 然后putenv
(或操作系統)有責任稍后釋放它。
putenv(strdup(settings.at(i).c_str()));
// ^^^^^^^ ^
由於putenv
不在 C 或 C++ 標准中,而是由 POSIX 提供,因此您應該檢查操作系統的聯機幫助頁以確保正確使用它。
該錯誤是由您調用 putenv() 引起的,它需要一個指向char
的指針。 您的向量包含 C++ 字符串 (std::string)...
你可以試試這個:
for (auto setting : settings) {
// ... putenv() is inconsistent across compilers, so use setenv() instead...
std::string key = item.substr( 0, item.find_first_of( "=" ) ) ;
std::string val = item.substr( key.length()+1 ) ;
if ( setenv( key.c_str(), val.c_str(), 1 ) != 0 ) {
cerr << "setenv(" << key << ',' << val << ") has failed: " << strerror( errno ) << endl;
}
}
從我讀過, putenv
應避免在新的代碼,並setenv
應該使用,因為它使得它的參數的副本,無論編譯器版本。
( setenv
在 stdlib.h 中)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.