execv()和constness [英] execv() and const-ness

查看:97
本文介绍了execv()和constness的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用C ++中的 execv()函数,但是如果一些参数是在C ++字符串中。它让我不能这样做:

I often use the execv() function in C++ but if some of the arguments are in C++ strings. It annoys me that I cannot do this:

const char *args[4];

args[0] = "/usr/bin/whatever";
args[1] = filename.c_str();
args[2] = someparameter.c_str();
args[3] = 0;

execv(args[0], args);

这不编译,因为execv()需要 char * const argv [] 这与const char *不兼容,所以我必须使用strdup()将我的std ::字符串复制到字符数组,这是一个痛苦。

This doesn't compile because execv() takes char *const argv[] which is not compatible with const char * so I have to copy my std::strings to character arrays using strdup() which is a pain.

有人知道原因是什么?

推荐答案

开放组基本规范解释了为什么这是:为了与现有的C代码兼容。无论是指针还是字符串内容本身都不打算改变。因此,在这种情况下,你可以使用 const_cast - c_str()的结果。

The Open Group Base Specifications explains why this is: for compatibility with existing C code. Neither the pointers nor the string contents themselves are intended to be changed, though. Thus, in this case, you can get away with const_cast-ing the result of c_str().

Quote:


关于 argv [] envp [] 是包含的常量,以便向未来语言绑定的写者明确这些对象是完全恒定的。由于ISO C标准的限制,不可能在标准C中说明这个想法。指定的两个级别 const argv [] envp [] exec函数的参数看起来是自然的选择,假设这些函数不修改数组的指针或函数指向的字符,但这将禁止现有的正确代码。

The statement about argv[] and envp[] being constants is included to make explicit to future writers of language bindings that these objects are completely constant. Due to a limitation of the ISO C standard, it is not possible to state that idea in standard C. Specifying two levels of const- qualification for the argv[] and envp[] parameters for the exec functions may seem to be the natural choice, given that these functions do not modify either the array of pointers or the characters to which the function points, but this would disallow existing correct code. Instead, only the array of pointers is noted as constant.

之后的表格和文本更有洞察力。但是,Stack Overflow不允许插入表,因此上面的引用应该是足够的上下文,以便在链接文档中搜索正确的位置。

The table and text after that is even more insightful. However, Stack Overflow doesn't allow tables to be inserted, so the quote above should be enough context for you to search for the right place in the linked document.

这篇关于execv()和constness的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆