为什么下面的程序会给出警告?
注意:很明显,将普通指针发送到需要 const 指针的函数不会给出任何警告。
#include <stdio.h>
void sam(const char **p) { }
int main(int argc, char **argv)
{
sam(argv);
return 0;
}
我得到以下错误,
In function `int main(int, char **)':
passing `char **' as argument 1 of `sam(const char **)'
adds cv-quals without intervening `const'
最佳答案
此代码违反了 const 的正确性。
问题在于此代码根本上是不安全的,因为您可能会无意中修改 const 对象。 C++ FAQ Lite 在对 "Why am I getting an error converting a 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!!
...
}
(示例来自 Marshall Cline 的 C++ FAQ Lite 文档,www.parashift.com/c++-faq-lite/)
您可以通过对两个间接级别进行 const 限定来解决此问题:
void sam(char const* const* p) { }
关于c++ - 为什么下面的程序会报错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3410663/