c++ - 为什么下面的程序会报错?

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

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

注意:很明显,将普通指针发送到需要 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/

相关文章:

mysql - 尝试包含 mysql-connector-c 时链接器出现 C 错误

c - 使用 Eclipse IDE 作为我的编程语言的文本编辑器

c - 尝试从 C 代码获取 Windows 版本

c - c代码中的段错误

c - 指向结构数组的指针 - 解释

c++ - aboutToQuit 期间的 Qt 异步操作

c++ - Xcode 5.0.1 中未报告段错误

c++ - 在 C++ 中为家庭作业创建 IntegerNumber 类,以将大整数求和为超出长范围的字符串

c++ - 将指针分配给 vector

c++ - 找不到 Protobuf(缺少 : Protobuf_PROTOC_EXECUTABLE)