为什么unique_ptr运算符->没有const重载? [英] Why is unique_ptr operator-> not const-overloaded?

查看:74
本文介绍了为什么unique_ptr运算符->没有const重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;

是指向的非 const 指针 const int 。您可以更改指针,但不能更改 int

is a non-const pointer to a const int. You can change the pointer but not the int.

现在,对于 unique_ptr 来说,这是一个问题,即 const 是在之内还是之外。 > 。因此:

Now, for unique_ptr, it's a question of whether the const goes inside or outside the <>. So:

std::unique_ptr<int> const u;

就像第一个。您可以更改 int ,但不能更改指针。

is like the first one. You can change the int, but not the pointer.

您想要的是:

std::unique_ptr<int const> u;

您可以更改指针,但不能更改 int 。或者甚至:

You can change the pointer, but not the int. Or perhaps even:

std::unique_ptr<int const> const u;

在这里您无法更改指针 int

Here you can't change the pointer or the int.

注意我如何始终放置 const 在右边?这有点罕见,但是在处理指针时是必需的。 const 始终适用于紧靠其左侧的东西,因为 * (指针为 const )或 int 。参见 http://kuhllib.com/2012/01/17/continental-const -placement /

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运算符-&gt;没有const重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆