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这个类型承诺不会改变数组的内容,但我仍然可以改变指针指向的位置。如果我这样做,我没有改变阵列,我也没有看到问题。
答案 0 :(得分:3)
这是一个古老的问题,直觉上你认为你可以添加const
ness"但实际上间接地添加const
ness 违反 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*
}
答案 1 :(得分:-1)
假设这是合法的。
char* inbufptr = buffer;
const char** inpufptrpos = &inbufptr;
现在您可以更改inbufptr
,但inpufptrpos
为const
,因此不应更改。你看,这没有多大意义。这就像const
没有得到尊重!
在this回答的帮助下,我希望这有帮助! :)