constamp; , amp; and amp;amp; specifiers for member functions in C++(常量amp;, amp;和amp;amp;C++ 中成员函数的说明符)
问题描述
最近我正在阅读 boost 的 API::optional
并遇到了以下问题:
Recently I was reading through the API of boost::optional
and came across the lines:
T const& operator *() const& ;
T& operator *() & ;
T&& operator *() && ;
我还编写了自己的程序,将成员函数定义为 const&、&和&&(请注意,我不是在谈论返回类型,而是在分号之前的说明符)并且它们似乎工作正常.
I also wrote my own program that defines member functions as const&, & and && (Note that I am not speaking about the return type, but the specifiers just before the semi-colons) and they seems to work fine.
我知道声明一个成员函数 const 是什么意思,但是谁能解释一下声明它是什么意思 const&, &和&&.
I know what it means to declare a member function const, but can anyone explain what it means to declare it const&, & and &&.
推荐答案
const&
表示,这个重载只会用于 const、non-const 和 lvalue 对象.
const&
means, that this overload will be used only for const, non-const and lvalue object.
const A a = A();
*a;
&
表示,这个重载将只用于非常量对象.
&
means, that this overload will be used only for non-const object.
A a;
*a;
&&
表示,这个重载将只用于右值对象.
&&
means, that this overload will be used only for rvalue object.
*A();
有关 C++11 标准的此功能的更多信息,您可以阅读这篇文章 什么是*this"的右值引用?
for more information about this feature of C++11 standard you can read this post What is "rvalue reference for *this"?
这篇关于常量&, &和&&C++ 中成员函数的说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:常量&, &和&&C++ 中成员函数的说明符


基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05