恒常性添加无效?错误:无法使用字符**初始化常量字符**

Invalid addition of constness? Error: Cannot use char** to initialize const char**

本文关键字:字符 初始化 常量 添加 常性 无效 错误      更新时间:2023-10-16

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

这是一个

古老的问题,直觉上你认为你可以"添加const性",但实际上添加const性间接违反了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*  
}
  • http://kera.name/articles/2009/12/a-question-on-indirect-constness/

假设这是合法的。

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

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

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