常量&, &和&&C++ 中成员函数的说明符

constamp; , amp; and amp;amp; specifiers for member functions in C++(常量amp;, amp;和amp;amp;C++ 中成员函数的说明符)
本文介绍了常量&, &和&&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++ 中成员函数的说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)