execv() 和常量 [英] execv() and const-ness

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

问题描述

我经常在 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::strings 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[]envp[] 参数似乎是自然的选择,因为这些函数既不修改指针数组也不修改函数指向的字符,但这将不允许存在正确的代码.相反,只有指针数组被标记为常量.

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() 和常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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