C++ : Meaning of const char*const*
C++ : Meaning of const char*const*
在一个C++程序中,我看到了一个函数原型:int Classifier::command(int argc, const char*const* argv)
const char*const* argv
是什么意思?它和const char* argv[]
一样吗?const char** argv
的意思也一样吗?
来自C++超级常见问题解答:
从右到左读取指针声明。
const X* p
表示"p
指向const
的X
":X
对象不能通过p
更改X* const p
表示"p
是指向non-const
的X
的const
指针":您不能更改指针p
本身,但可以通过p
更改X
对象const X* const p
表示"p是指向const
的X
的const
指针":您不能更改指针p
本身,也不能通过p
更改X
对象哦,是的,我有没有提到从右到左阅读你的指针声明?
const char * const *
与char const * const *
相同:指向常量字符的常量指针的(非常量)指针。
const char *
与char const *
相同:指向常量字符的(非常量)指针。
const char * *
与char const * *
相同:一个指向常量字符的(非常量)指针。
不,它与const char *argv[]
不同。const
禁止在特定的去引用级别修改去引用值:
**argv = x; // not allowed because of the first const
*argv = y; // not allowed because of the second const
argv = z; // allowed because no const appears right next to the argv identifier
const char*const* argv
表示"指向常量的指针指向常量char
"。它与const char *argv[]
"不一样",但在某种程度上是兼容的:
void foo(const char *const *argv);
void bar(const char **argv)
{
foo(argv);
}
编译得很好。(如果没有const_cast
,反向就无法编译。)
一个不改变的指针变成一个不变的字符串:
const char* aString ="testString";
aString[0] = 'x'; // invaliv since the content is const
aString = "anotherTestString"; //ok, since th content doesn't change
const char const* bString = "testString";
bString [0] = 'x'; still invalid
bString = "yet another string"; // now invalid since the pointer now too is const and may not be changed.
const char*const* a;
基本上说:a
是指向不可更改常量字符指针的指针。
所以这将是一个有效的代码:
const const const char*const*const* a;