为什么以下程序会出错?

jos*_*osh 3 c c++ pointers const command-line-arguments

为什么以下程序会发出警告?

注意:很明显,向需要const指针的函数发送普通指针不会发出任何警告.

#include <stdio.h>
void sam(const char **p) { }
int main(int argc, char **argv)
{
    sam(argv);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误,

In function `int main(int, char **)':
passing `char **' as argument 1 of `sam(const char **)' 
adds cv-quals without intervening `const'
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 10

此代码违反了const正确性.

问题是这段代码基本上是不安全的,因为你可能无意中修改了一个const对象.在C++ FAQ精简版有一个很好的例子在回答"为什么我会得到一个错误转换Foo**Foo const**?"

class Foo {
 public:
   void modify();  // make some modify to the this object
 };

 int main()
 {
   const Foo x;
   Foo* p;
   Foo const** q = &p;  // q now points to p; this is (fortunately!) an error
   *q = &x;             // p now points to x
   p->modify();         // Ouch: modifies a const Foo!!
   ...
 }
Run Code Online (Sandbox Code Playgroud)

(来自Marshall Cline的C++ FAQ Lite文档,www.parashift.com / c + + - faq-lite/)

您可以通过const限定两个间接级别来解决问题:

void sam(char const* const* p) { }
Run Code Online (Sandbox Code Playgroud)