c++ - 为什么 unique_ptr operator-> 不是 const-overloaded?

标签 c++ constants smart-pointers

std::unique_ptr::operator-> 有签名

pointer operator->() const noexcept;

所以 operator-> 是 const 但返回一个可变指针。这允许如下代码:

void myConstMemberFunction() const
{
    myUniquePtrMember->nonConstFunction();
}

为什么标准允许这样做,以及防止上述使用的最佳方法是什么?

最佳答案

把它想象成一个普通的指针:

int * const i;

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

int const * i;

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


现在,对于 unique_ptr , 问题是 const进入<> 内部或外部.所以:

std::unique_ptr<int> const u;

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

你想要的是:

std::unique_ptr<int const> u;

您可以更改指针,但不能更改 int .甚至可能:

std::unique_ptr<int const> const u;

这里你不能改变指针 int .


请注意我总是如何放置 const在右侧?这有点不常见,但在处理指针时是必要的。 const总是适用于紧靠其左侧的事物,即 * (指针是 const ),或 int .见 http://kuhllib.com/2012/01/17/continental-const-placement/ .

写作 const int , 可能会让你想到 int const *const -指向非const的指针int ,这是错误的。

关于c++ - 为什么 unique_ptr operator-> 不是 const-overloaded?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34334043/

相关文章:

c++ - C/C++结构问题

c++ - 我如何在 Visual C++ 中表示巨大的 float

c# - 在 C# 中使用枚举作为整型常量

c++ - 智能指针与自动引用计数

c++ - 错误 C2679 : binary '<<' : no operator found which takes a right-hand operand of type 'mystring' (or there is no acceptable conversion)

c++ - 后续: What exactly is a variable in C++14/C++17?

c++ - 是否有任何内置的 CUDA 函数允许 CUDA 内核向主机代码报告错误?

string - Swift String 常量的类型是否与 String 文字不同?

c++ - const c++ 的正确使用

c++ - shared_ptr 魔法 :)