【问题标题】:Why does the following program give a error?为什么下面的程序会报错?
【发布时间】:2011-03-25 13:13:09
【问题描述】:

为什么下面的程序会给出警告?

注意:很明显,向需要 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'

【问题讨论】:

  • 您的编译器是否报告错误或警告? (而且,如果它只是报告一个警告,那么您使用的是什么编译器?它应该报告一个错误)
  • @James:我的编译器 [gcc 版本 2.95.3] 抛出错误。将立即编辑问题。感谢您的通知。
  • @Prabhu:啊,好的。我最初认为它可能是 Visual C++ 的旧版本(我认为 Visual C++ 缺乏其标准一致性……一点也不……不……)。跨度>
  • 我不是 C++ 专家,但我会注意到你的编译器已经快 10 年了。 :-)
  • 我正在使用 gcc 4.1.2(2007 年 2 月 13 日发布),它给了我一个警告?

标签: c++ c pointers constants command-line-arguments


【解决方案1】:

此代码违反了 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) { }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多