execv() 和常量 [英] execv() and const-ness
问题描述
我经常在 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::string
复制到字符数组,这很痛苦.
This doesn't compile because execv()
takes char *const argv[]
which is not compatible with const char *
, so I have to copy my std::string
s to character arrays using strdup()
, which is a pain.
有人知道这是什么原因吗?
Does anyone know the reason for this?
推荐答案
Open Group Base Specifications 解释了原因:为了与现有 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()
.
关于 argv[]
和 envp[]
是常量的声明被包含在内,以向未来的语言绑定作者明确这些对象是完全常量.由于 ISO C 标准的限制,不可能在标准 C 中说明这个想法.指定两个级别的 const
- argv[]
和
The statement about
argv[]
andenvp[]
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 ofconst
- qualification for theargv[]
andenvp[]
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() 和常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!