【问题标题】:Invalid addition of constness? Error: Cannot use char** to initialize const char**常量添加无效?错误:不能使用 char** 来初始化 const char**
【发布时间】:2014-12-31 11:17:07
【问题描述】:

Solaris Studio 正在生成最令人费解的错误消息。

158 char* inbufptr = buffer;
159 char* outbufptr = outbuf;
160 
161 const char** inbufptrpos = &inbufptr;

错误信息是:

第 161 行:错误:无法使用 char** 来初始化 const char**。

为什么添加常量会成为问题?我卡住了,请帮帮我...


 memory: [m y _ c h a r _ a r r a y | inbufptr | inbufptr_pos]
          ^                           ^
          | (1)                       | (2)
          inbufptr                    inbufptrpos

指针 char* inbufptr 指向数组的开头,并且不承诺保持任何常量。

现在,如果我现在有一个指针 char const **inbufptr_pos 这种类型保证不会更改数组的内容,但我仍然可以更改指针指向的位置。如果我这样做,我没有更改数组,我认为这没有问题。

【问题讨论】:

    标签: c++ solaris solaris-studio


    【解决方案1】:

    这是一个古老的问题,直觉上你认为你可以“添加constness”,但实际上添加constness 间接 违反 @ 987654324@-正确性。

    标准本身甚至有一个例子来帮助人们回到正确的道路上:

    #include <cassert>  
    
    int main() {  
      char* p = 0;  
    
      //char const** a = &p; // not allowed, but let's pretend it is  
      char const** a = (char const**)&p; // instead force the cast to compile  
    
      char const* orig = "original";  
      *a = orig; // type of *a is char const*, which is the type of orig, this is allowed  
    
      assert(p == orig); // oops! char* points to a char const*  
    }
    

    【讨论】:

    • 与此相比,我的回答并没有那么糟糕,或者是吗?我不在乎名誉,我只想看看我的错误。你能看看吗? :)
    • @G.Samaras:你没有完全理解这个例子。
    • 您能否解释一下原因,以便我从错误中吸取教训? :)
    • @G.Samaras:研究这个你就会明白!
    • @G.Samaras: 提示:inpufptrpos 不是问题(例如,你可以拥有int x = 5; const int* ptr = &amp;x; x = 6; 并且没有问题——这相当于你的示例)
    【解决方案2】:

    假设这是合法的。

    char* inbufptr = buffer;
    
    const char** inpufptrpos = &inbufptr;
    

    现在您可以更改inbufptr,但inpufptrposconst,因此不应更改。你看这没有多大意义。这就像const 不受尊重!

    this答案的帮助下,希望对您有所帮助! :)

    【讨论】:

    • 是的,我没想到,谢谢,顺便问一下@Beginner,+1!
    猜你喜欢
    • 2015-08-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2022-11-23
    • 2015-01-04
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    相关资源
    最近更新 更多