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

Ahm*_*hid 6 c++ c++11

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

int *p1;

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

但是,如果我使用"int*"而不是"decltype(p1)",则编译器会标记错误.

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

error: assignment of read-only location ‘* p2’
  *p2 = 200;
      ^
Run Code Online (Sandbox Code Playgroud)

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

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

M.M*_*M.M 10

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);
Run Code Online (Sandbox Code Playgroud)


Pra*_*han 5

std::pointer_traits在这里会派上用场。std::pointer_traits::element_typestd::pointer_traits::rebind允许您编写一个通用表达式,该表达式适用于任何类似指针的类型:

using element_type = std::pointer_traits<decltype(p1)>::element_type;
using pointer_like_to_const = std::pointer_traits<decltype(p1)>::rebind<std::add_const_t<element_type>>;
pointer_like_to_const p2 = new int(100);
Run Code Online (Sandbox Code Playgroud)

请注意,即使p1shared_ptr<int>或 ,此代码也可以工作unique_ptr<int>