C++ : Meaning of const char*const*

C++ : Meaning of const char*const*

本文关键字:const char of Meaning C++      更新时间:2023-10-16

在一个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指向constX":X对象不能通过p更改
  • X* const p表示"p是指向non-constXconst指针":您不能更改指针p本身,但可以通过p更改X对象
  • const X* const p表示"p是指向constXconst指针":您不能更改指针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;