问题描述
std :: unique_ptr :: operator->
具有签名
pointer operator->() const noexcept;
所以 operator->
是const但返回一个可变的指针。这允许使用以下代码:
So operator->
is const but returns a mutable pointer. This allows for code like:
void myConstMemberFunction() const
{
myUniquePtrMember->nonConstFunction();
}
为什么标准允许这样做,防止使用的最佳方法是什么
Why does the standard allow this, and what is the best way to prevent usage as presented above?
推荐答案
像普通指针一样思考它:
Think about it like a normal pointer:
int * const i;
是 const
指针,指向非 const
int
。您可以更改 int
,但不能更改指针。
is a const
pointer to a non-const
int
. You can change the int
, but not the pointer.
int const * i;
是指向。
Notice how I always place the const
on the right? This is a little uncommon, but is necessary when dealing with pointers. The const
always applies to the thing immediately to its left, be that the *
(pointer is const
), or the int
. See http://kuhllib.com/2012/01/17/continental-const-placement/ .
写 const int
,可能会导致您想到 int const *
是 const
指向非 const
<$ c的指针$ c> int ,这是错误的。
Writing const int
, might lead you to thinking int const *
is a const
-pointer to a non-const
int
, which is wrong.
这篇关于为什么unique_ptr运算符->没有const重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!