【问题标题】:const Class * const Function() What does the second const do? [duplicate]const类* const函数()第二个const做什么? [复制]
【发布时间】:2016-06-19 09:56:35
【问题描述】:

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

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

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

const SimpleClass * const Myfunction()
{
   SimpleClass * sc;
   return sc;
}

【问题讨论】:

  • 确实返回一个指向常量对象的常量指针。您可以将该指针的 复制到非常量变量。 (与const int f() { return 0; } int main() { int x = f(); x = 1; }原理相同。)
  • 想要另一个 const?将其添加到 MyFunction() 行的末尾。 ;)

标签: c++ pointers c++11 reference constants


【解决方案1】:
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

【讨论】:

  • 谢谢,现在更有意义了。
【解决方案2】:

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

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

您可能对Purpose of returning by const value?What are the use cases for having a function return by const value for non-builtin type? 感兴趣

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 2021-12-13
    • 2014-02-15
    • 1970-01-01
    • 2010-11-11
    相关资源
    最近更新 更多