c++ - 将 const 和 decltype 与指针变量一起使用

标签 c++ c++11

下面的代码允许我更改 *p2 的值,即使 p2 是用 const 声明的。

int *p1;

const decltype(p1) p2 = new int(100);
*p2 = 200;
cout << "*p2: " << *p2 << endl; // Outputs *p2: 200

但是,如果我使用“int *”而不是“decltype(p1)”,那么编译器会标记错误。

const int * p2 = new int(100);
*p2 = 200;
cout << "*p2: " << *p2 << endl;

error: assignment of read-only location ‘* p2’
  *p2 = 200;
      ^

我正在使用 g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2。

应用于指针变量时,decltype 是否忽略 const 说明符?

最佳答案

const decltype(p1) p2 表示 int* const p2

这意味着您不能更改p2,但您可以更改所指向的内容。


const T 总是将 const 应用于 T 的所谓“顶层”。当 T 是复合类型(即,从基本类型集构建的类型)时,如果要将 const 应用于较低的水平。

当 T 是 int * 时,添加顶级 const 将得到 int * const* 划定一个层次;要获取 * 下面的内容,您必须手动删除 *,应用 const,然后放入 * 返回。

一个可能的解决方案是:

const std::remove_pointer<decltype(p1)>::type *p2 = new int(100);

关于c++ - 将 const 和 decltype 与指针变量一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28575219/

相关文章:

c++ - std::vector 在 push_back 期间多次调用析构函数?

c++ - std::aligned_storage 的分配目标(堆栈或堆?)

c++ - 为什么这个编译: string = int

c++ - 从文件中读取和写入 int 对

c++ - 此文件需要 C++11 库支持

c++ - Multimap 和 shared_ptr

c++ - 可变参数模板扩展中的函数调用顺序

c++ - 在c++中找到用户输入的3个最大数字的平均值

c++ - 使用 libcurl 发送 post 请求

c++ - 直观的线程安全