恒常性添加无效?错误:无法使用字符**初始化常量字符**
Invalid addition of constness? Error: Cannot use char** to initialize const char**
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
,但inpufptrpos
是const
的,因此不应该更改。你看这没有多大意义。就像const
不被尊重一样!
在这个答案的帮助下,我希望这有所帮助! :)
相关文章:
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 使用 cin.get() 初始化字符数组
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 初始化常量字符* 数组
- 递增 'int i = 0' 以在初始化的字符数组的位置递增
- 在函数内初始化无符号字符指针将返回空指针
- 当我们不使用空字符显式初始化字符数组时,字符串的长度是多少?
- 如何在 C++ 中使用 NULL(或 0)初始化静态字符数组
- 从 C++ 中的位表示形式初始化字符
- C++结构字符数组初始化
- 成本字符*类型的非常量引用的无效初始化,并且来自常量字符*类型的临时引用
- 初始化字符*
- 使用另一个字符数组进行字符初始化
- C 字符初始化允许多个字符
- 如何使用包含空值的字符*初始化 std::string
- 恒常性添加无效?错误:无法使用字符**初始化常量字符**
- 用"*"(特殊字符)初始化向量,然后打印出来
- 通过连接另一个字符*初始化const字符*
- 字符初始化问题
- 使用字符 c++ 初始化 2D 数组