[英]Using const and decltype with a pointer variable
The following code allows me to change the value at *p2 even though p2 is declared with const. 以下代码允许我更改* p2处的值,即使p2是用const声明的。
int *p1;
const decltype(p1) p2 = new int(100);
*p2 = 200;
cout << "*p2: " << *p2 << endl; // Outputs *p2: 200
However, if I use "int *" instead of "decltype(p1)", then the compiler flags an error. 但是,如果我使用“int *”而不是“decltype(p1)”,则编译器会标记错误。
const int * p2 = new int(100);
*p2 = 200;
cout << "*p2: " << *p2 << endl;
error: assignment of read-only location ‘* p2’
*p2 = 200;
^
I am using g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2. 我正在使用g ++(Ubuntu 4.8.2-19ubuntu1)4.8.2。
Does decltype ignore const specifier when applied on pointer variable? 当应用于指针变量时,decltype是否忽略const说明符?
const decltype(p1) p2
means int* const p2
. const decltype(p1) p2
表示int* const p2
。
This means that you cannot change p2
, but you may change the things being pointed to. 这意味着您无法更改p2
,但您可以更改指向的内容。
const T
always applies const to the so-called "top level" of T
. const T
总是适用于常量的所谓“顶级” T
。 When T
is a composite type (that is, a type built up from the basic set of types) then you will have to jump through hoops if you want to apply const
to the lower levels. 当T
是复合类型(即,从基本类型集构建的类型)时,如果要将const
应用于较低级别,则必须跳过箍。
When T is int *
, adding top level const would give int * const
. 当T为int *
,添加顶级const将给出int * const
。 The *
demarcates a level; *
划分一个级别; to get at the stuff below the *
you have to manually remove the *
, apply const
, then put the *
back. 得到*
以下的东西你必须手动删除*
,应用const
,然后把*
放回去。
A possible solution is: 可能的解决方案是:
const std::remove_pointer<decltype(p1)>::type *p2 = new int(100);
std::pointer_traits
would come in handy here. std::pointer_traits
在这里会派上用场。 std::pointer_traits::element_type
and std::pointer_traits::rebind
allow you to write a generic expression which will work well for any pointer-like type: std::pointer_traits::element_type
和std::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);
Note that this code would work even if p1
was shared_ptr<int>
or unique_ptr<int>
. 请注意,即使p1
是shared_ptr<int>
或unique_ptr<int>
,此代码也能正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.