1

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

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

错误信息是:

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

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


 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 这种类型保证不会更改数组的内容,但我仍然可以更改指针指向的位置。如果我这样做,我没有更改数组,我看不出有什么问题。

4

2 回答 2

3

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

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

#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*  
}
于 2014-12-31T16:32:02.283 回答
-1

假设这是合法的。

char* inbufptr = buffer;

const char** inpufptrpos = &inbufptr;

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

这个答案的帮助下,我希望这会有所帮助!:)

于 2014-12-31T16:09:38.143 回答