[英]Why does the following program give a error?
Why does the following program give a warning? 为什么以下程序会发出警告?
Note : Its obvious that sending a normal pointer to a function requiring const pointer does not give any warning. 注意 :显而易见的是,向需要const指针的函数发送普通指针不会发出任何警告。
#include <stdio.h>
void sam(const char **p) { }
int main(int argc, char **argv)
{
sam(argv);
return 0;
}
I get the following error, 我收到以下错误,
In function `int main(int, char **)':
passing `char **' as argument 1 of `sam(const char **)'
adds cv-quals without intervening `const'
This code violates const correctness. 此代码违反了const正确性。
The issue is that this code is fundamentally unsafe because you could inadvertently modify a const object. 问题是这段代码基本上是不安全的,因为你可能无意中修改了一个const对象。 The C++ FAQ Lite has an excellent example of this in the answer to "Why am I getting an error converting a
Foo**
→ Foo const**
?" C ++ FAQ Lite在“为什么我在转换
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!!
...
}
(Example from Marshall Cline's C++ FAQ Lite document, www.parashift.com/c++-faq-lite/ ) (来自Marshall Cline的C ++ FAQ Lite文档, www.parashift.com / c + + - faq-lite /)
You can fix the problem by const-qualifying both levels of indirection: 您可以通过const限定两个间接级别来解决问题:
void sam(char const* const* p) { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.