为什么当我从堆中获取内存时,我可以改变const int**类型的int*值



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
~~~ ^

BUT:如果我处理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得到相同的结果?

在某些情况下,这个网站https://cdecl.org/的C语法也可以帮助c++。:

const int *const* pp 

它告诉我:

声明pp为指向const int的指针

:

const int **pp1

它告诉我:

声明pp1为指向const int的指针的指针

让我们使用....

*pp = ... // ERROR !

当你对pp解引用时,你会得到一个指向const into的const指针。(因为pp是指向const的指针,指向const int)。不能分配给const whatever。什么算顶级const!

*pp1 ... // OK !?!

当你对pp1解引用时,你会得到一个指向const int"(因为pp1是指向指向const int的指针的指针)。指向const int的指针不是常量。最重要的是顶级const!它指向const int,但指针本身不是const

结论:你的两个版本之间的区别不是使用new,而是你解引用的指针的类型(然后尝试传递给指针)。

最新更新