Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c++11 - const& , & and && specifiers for member functions in C++

Recently I was reading through the API of boost::optional and came across the lines:

T const& operator *() const& ;
T&       operator *() & ;
T&&      operator *() && ;

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.

I know what it means to declare a member function const, but can anyone explain what it means to declare it const&, & and &&.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

for more information about this feature of C++11 standard you can read this post What is "rvalue reference for *this"?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...