为什么从堆中获取内存时可以更改 const int** 类型中 int* 的值
Why can i change value of int* in const int** type when getting memory from heap
const
限定词有一些问题。
我试过这样做:
int a{ 3 };
int *p{ &a };
//const int **pp{ &p }; // FIXME: Compiler demands that p must have a const int *type
const int *const* pp{ &p }; // works here but it means, that I have a pointer to the const pointer to the const value
*pp = nullptr; // doesn't work cause of upper type
结果错误:
<source>:8:5: error: read-only variable is not assignable
*pp = nullptr; // doesn't work cause of upper type
~~~ ^
但是:如果我处理 new
它会很有趣
const int **pp1{ new const int* {&p} }; // Here I have a poiner to pointer to const int, so I can change it
*pp1 = nullptr; // works
那么,为什么编译器需要 const int* const*
?编译器 - MSVC,标准 - c++17
更新:
const int *p{ nullptr };
const int **pp{ &p }; // My intention
*pp = nullptr; // it works cause pointer non - const
但是在 const int *p
中没有 const 我怎么能得到相同的结果呢?
在某些情况下,此 C 语法站点 https://cdecl.org/ 也可以帮助 C++。为此:
const int *const* pp
它告诉我:
declare pp as pointer to const pointer to const int
为此:
const int **pp1
它告诉我:
declare pp1 as pointer to pointer to const int
让我们用那个....
*pp = ... // ERROR !
当您取消引用 pp
时,您会得到一个“指向 const int 的 const 指针”(因为 pp
是“指向 const 的指针,指向 const int”)。您不能分配给 const whatever
。什么算顶级const
!
*pp1 ... // OK !?!
当您取消引用 pp1
时,您会得到一个“指向 const int 的指针”(因为 pp1
是一个“指向 const int 的指针”)。指向 const int
的指针不是常量。算的是顶级const
!它指向 const int
但指针本身不是 const
.
结论:你的两个版本之间的区别不是new
的使用,而是你取消引用的指针的类型(然后尝试分配给指针对象)。
const
限定词有一些问题。
我试过这样做:
int a{ 3 };
int *p{ &a };
//const int **pp{ &p }; // FIXME: Compiler demands that p must have a const int *type
const int *const* pp{ &p }; // works here but it means, that I have a pointer to the const pointer to the const value
*pp = nullptr; // doesn't work cause of upper type
结果错误:
<source>:8:5: error: read-only variable is not assignable
*pp = nullptr; // doesn't work cause of upper type
~~~ ^
但是:如果我处理 new
它会很有趣
const int **pp1{ new const int* {&p} }; // Here I have a poiner to pointer to const int, so I can change it
*pp1 = nullptr; // works
那么,为什么编译器需要 const int* const*
?编译器 - MSVC,标准 - c++17
更新:
const int *p{ nullptr };
const int **pp{ &p }; // My intention
*pp = nullptr; // it works cause pointer non - const
但是在 const int *p
中没有 const 我怎么能得到相同的结果呢?
在某些情况下,此 C 语法站点 https://cdecl.org/ 也可以帮助 C++。为此:
const int *const* pp
它告诉我:
declare pp as pointer to const pointer to const int
为此:
const int **pp1
它告诉我:
declare pp1 as pointer to pointer to const int
让我们用那个....
*pp = ... // ERROR !
当您取消引用 pp
时,您会得到一个“指向 const int 的 const 指针”(因为 pp
是“指向 const 的指针,指向 const int”)。您不能分配给 const whatever
。什么算顶级const
!
*pp1 ... // OK !?!
当您取消引用 pp1
时,您会得到一个“指向 const int 的指针”(因为 pp1
是一个“指向 const int 的指针”)。指向 const int
的指针不是常量。算的是顶级const
!它指向 const int
但指针本身不是 const
.
结论:你的两个版本之间的区别不是new
的使用,而是你取消引用的指针的类型(然后尝试分配给指针对象)。