const 类 * const Function() 第二个 const 是做什么的

const Class * const Function() What does the second const do?

本文关键字:const 什么 第二个 Function      更新时间:2023-10-16

第二个常量在下面的结构中做什么?(这只是一个示例函数)。

我知道第一个常量使函数返回一个常量对象。但是我无法弄清楚标识符之前的常量是做什么的。

首先,虽然它返回了一个指向常量对象的常量指针,但我仍然能够重新分配返回的指针,所以我想情况并非如此。

const SimpleClass * const Myfunction()
{
   SimpleClass * sc;
   return sc;
}
const SimpleClass * const Myfunction()
{   
    return sc;
}
decltype(auto) p = Myfunction();
p = nullptr; // error due to the second const.

但事实是,没有多少人使用 decltype(auto),并且您的函数通常会像这样调用:

const SimpleClass *p = Myfunction();
p = nullptr; // success, you are not required to specify the second const.
const auto* p = Myfunction();
p = nullptr; // success, again: we are not required to specify the second const.

和。。。

const SimpleClass * const p = Myfunction();
p = nullptr; // error
const auto* const p = Myfunction();
p = nullptr; // error

const表示返回的指针本身是常量,而前const表示内存不可修改。

返回的指针是临时值(右值)。这就是为什么它是否const并不重要,因为它无论如何都无法修改:Myfunction()++;错了。"感受"第二const的一种方法是使用decltype(auto) p = Myfunction();并尝试修改p,正如何塞指出的那样。

您可能对按常量值返回的目的感兴趣?以及让函数按常量值返回非内置类型的用例是什么?