【问题标题】:Why is it not possible to implicitly convert char** to const char ** [duplicate]为什么不能将 char** 隐式转换为 const char ** [重复]
【发布时间】:2013-03-20 04:37:52
【问题描述】:

我有一个或多或少的代码:

bar(const char**)
{
// stuff
}

foo(char** arr)
{
  bar(arr);
}

编译器通知我我正在执行invalid conversion from ‘char**’ to ‘const char**’。虽然我知道这意味着什么,但我不明白为什么不允许这样做。在需要const char* 的地方传递char* 是完全可以的。

【问题讨论】:

标签: c++ casting char


【解决方案1】:

如果允许的话,可能会导致类似的情况。

void foo(int** arr)
{
    /*Can freely modify value at location pointed by a*/
   **arr = 6;
}


int main()
{
 /*Pointer to constant*/
 int i = 5;

 const int* a =&a;

 /*Not a pointer to constant*/
 int** aa= &a;

 foo(aa);

return 0;
}

【讨论】:

    【解决方案2】:

    因为如果允许,那么您可能会无意中更改声明为 const 的内容。

    这是一个具体的滥用示例,如果规则允许的话:

    char const* s = "a literal, very const";
    
    bar(const char** pp )
    {
        *pp = s;
    }
    
    foo(char** arr)
    {
      bar(arr);
      char* unconsted_s = *arr;
      unconsted_s[0] = 'X';
    }
    

    这也是FAQ。在询问之前检查常见问题解答(或只是谷歌)通常是个好主意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      相关资源
      最近更新 更多