C ++:char **到const char **转换 [英] C++: char** to const char** conversion
问题描述
在C ++中,为什么不能将 char **
作为参数传递给接受 const char **
,从
char *
到 const char *
的转换是可能的, p>
In C++, why is it not possible to pass a char**
as an argument to a function that accepts const char**
, when a conversion from char*
to const char*
is possible, as shown below
void f1(const char** a)
{
}
void f2(const char* b)
{
}
int main(int argc, char const *argv[])
{
char* c;
f1(&c); // doesn't work
f2(c); //works
return 0;
}
编译器输出为
test.cpp: In function 'int main(int, const char**)':
test.cpp:15:10: error: invalid conversion from 'char**' to 'const char**' [-fpermissive]
test.cpp:1:6: error: initializing argument 1 of 'void f1(const char**)' [-fpermissive]
推荐答案
您需要在指针的两个取消引用层次上保护内容。使用 const char **
,您可以实际修改第一个引用的内容。
You need to protect contents on both levels of dereference of the pointer. With const char**
you could actually modify contents on the 1st dereference.
char *tmp = "foo"; //Deprecated but it's ok for the example
void f1(const char** a)
{
a[0] = tmp; //this is legal
a[0][1] = 'x'; //this is not
}
这很可能不是想要的。它应该看起来像这样:
And this is most probably not intended. It should look like this:
char *tmp = "foo"; //Deprecated but it's ok for the example
void f1(char const* const* a)
{
a[0] = tmp; // this is not legal any more
a[0][1] = 'x'; // this still upsets compiler
}
编译器不允许隐式转换为这样的部分保护的指针类型。允许此类转换可能会产生讨厌的后果,如 c ++ faq
在@zmb的评论中指出。此回答还引用了如何允许违反对象的 constness (如果允许),使用 char
示例。
The compiler does not allow implicit conversion to such "partially" protected pointer types. Allowing such conversion could have nasty consequences as discussed in c++faq
pointed out in comment by @zmb. This answer also cites how could you violate constness of an object if this was allowed, using char
examples.
然而,可以隐式转换为第二个代码示例中所示的完全以下代码编译。
One can however implicitly convert to a "fully" protected pointer as shown in the 2nd code example so below code compiles.
void f1(char const* const* a){}
void f2(const char* b){}
int main(int argc, char const *argv[])
{
char* c;
f1(&c); // works now too!
f2(c); // works
return 0;
}
实际上有很多关于这件事的问题和答案。例如:
Actually there is a bunch of questions and answers on this matter lying around. E.g:
- invalid conversion from ‘char**’ to ‘const char**’
- Why am I getting an error converting a ‘float**’ to ‘const float**’?
编辑:我第一个例子错了一点。感谢指出!
I got the 1st example wrong by a bit. Thank for pointing it out!
这篇关于C ++:char **到const char **转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!