const 类 * const Function() 第二个 const 是做什么的
const Class * const Function() What does the second const do?
第二个常量在下面的结构中做什么?(这只是一个示例函数)。
我知道第一个常量使函数返回一个常量对象。但是我无法弄清楚标识符之前的常量是做什么的。
首先,虽然它返回了一个指向常量对象的常量指针,但我仍然能够重新分配返回的指针,所以我想情况并非如此。
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
,正如何塞指出的那样。
您可能对按常量值返回的目的感兴趣?以及让函数按常量值返回非内置类型的用例是什么?
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 在C++17中,引用const字符串的语义应该是什么
- 违反const正确性:我应该现实地期待什么问题
- 如果我在 const 函数上使用指针,我可以返回什么?
- 在只读(即 const)访问器上执行结构化绑定的最佳实践是什么?
- 使用 const char* 初始化 const ref 字符串成员时幕后会发生什么
- 什么是常量指针常量引用类型的参数?(const X* const & p)
- 在C++中,从构造函数中将字符串文本分配给成员const char*变量时会发生什么
- "char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {"剂量是什么意思
- 语法问题:"char [5] const &"是什么意思?
- 有什么陷阱用 constexpr string_view 替换全局 const char[]?
- 在什么情况下,使用'const T*'输入参数比'const T&'更可取?
- 在 c++ 中,char *p 和 const char * p 有什么区别?
- 'note: 候選人: Volume& Volume::operator=(const Volume&)'.这个错误是什么?
- 有什么理由在函数中使用 const 吗?
- C++:在函数参数的上下文中,"const T &"和"T &&"有什么区别?
- 在下面函数的返回中添加 const 限定符的重要性是什么?
- 明确定义'static const variable in a struct'对C++ 11 及以上有什么影响吗?
- int(int)& 或 int(int) const &是什么类型?
- 这个(const vector<vector<int> > &A)"代码段是什么意思?