【发布时间】:2011-05-01 06:41:13
【问题描述】:
我想将一个向量作为第二个参数传递给 execvp。有可能吗?
【问题讨论】:
我想将一个向量作为第二个参数传递给 execvp。有可能吗?
【问题讨论】:
是的,通过利用向量使用的内部数组,它可以非常干净地完成。
这会起作用,因为标准保证其元素是连续存储的(请参阅https://stackoverflow.com/a/2923290/383983)
#include <vector>
using namespace std;
int main(void) {
vector<char *> commandVector;
// do a push_back for the command, then each of the arguments
commandVector.push_back("echo");
commandVector.push_back("testing");
commandVector.push_back("1");
commandVector.push_back("2");
commandVector.push_back("3");
// push NULL to the end of the vector (execvp expects NULL as last element)
commandVector.push_back(NULL);
// pass the vector's internal array to execvp
char **command = &commandVector[0];
int status = execvp(command[0], command);
return 0;
}
【讨论】:
deprecated conversion from string constant to ‘std::vector<char*>::value_type {aka char*}’ [-Wwrite-strings] 将字符串常量推送到commandVector 的警告有什么建议吗?
是的,它可以通过利用向量使用的内部数组来完成。
这会起作用,因为标准保证其元素是连续存储的(请参阅https://stackoverflow.com/a/2923290/383983)
#include <vector>
using std::vector;
int main() {
vector<char*> commandVector;
// do a push_back for the command, then each of the arguments
commandVector.push_back(const_cast<char*>("echo"));
commandVector.push_back(const_cast<char*>("testing"));
commandVector.push_back(const_cast<char*>("1"));
commandVector.push_back(const_cast<char*>("2"));
commandVector.push_back(const_cast<char*>("3"));
// push NULL to the end of the vector (execvp expects NULL as last element)
commandVector.push_back(NULL);
int status = execvp(command[0], &command[0]);
return 0;
}
执行 const_cast 以避免“从字符串常量到 'char*' 的不推荐转换”。字符串文字在 C++ 中实现为“const char*”。 const_cast 是这里最安全的强制转换形式,因为它只删除了 const 而没有做任何其他有趣的事情。 execvp 无论如何都不会编辑这些值。
如果您想避免所有类型转换,则必须通过将所有值复制到不值得的 'char*' 类型来使代码复杂化。
【讨论】:
不是直接的;您需要以某种方式将向量表示为以 NULL 结尾的字符串指针数组。如果它是一个字符串向量,那很简单;如果是其他类型的数据,您必须弄清楚如何将其编码为字符串。
【讨论】: