C++ : Meaning of const char*const*

帅比萌擦擦* 提交于 2019-12-08 23:25:01

问题


In one of the C++ programs, I saw a function prototype : int Classifier::command(int argc, const char*const* argv)

What does const char*const* argv mean? Is it the same as const char* argv[]? Does const char** argv also mean the same?


回答1:


No, it's not the same as const char *argv[]. The const prohibits modifications of the dereferenced value at the particular level of dereferencing:

**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



回答2:


const char*const* argv means "pointer to constant pointer to constant char". It's not "the same" as const char *argv[], but it is compatible to some extent:

void foo(const char *const *argv);

void bar(const char **argv)
{
    foo(argv);
}

compiles just fine. (The reverse wouldn't compile without a const_cast.)




回答3:


From the C++ Super-FAQ:

Read the pointer declarations right-to-left.

  • const X* p means "p points to an X that is const": the X object can't be changed via p.
  • X* const p means "p is a const pointer to an X that is non-const": you can't change the pointer p itself, but you can change the X object via p.
  • const X* const p means "p is a const pointer to an X that is const": you can't change the pointer p itself, nor can you change the X object via p.

And, oh yea, did I mention to read your pointer declarations right-to-left?

const char * const * is the same as char const * const *: a (non-const) pointer to a const pointer to a const char.

const char * is the same as char const *: a (non-const) pointer to a const char.

const char * * is the same as char const * *: a (non-const) pointer to a (non-const) pointer to a const char.




回答4:


A pointer that does not change to a string that does not change:

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.


来源:https://stackoverflow.com/questions/10029170/c-meaning-of-const-charconst

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!