In the given code snippet:
class wrap { operator obj() const & { ... } //Copy from me. operator obj() && { ... } //Move from me. };
we encounter two member function declarations with different ref-qualifiers (& and &&). However, what does the single ampersand (&) signify?
The single ampersand in a non-static member function declaration indicates that the member function is invoked when the object is an lvalue reference. By default, non-static member functions can be invoked on both lvalue and rvalue objects. However, by specifying &, the function can only accept lvalues.
To illustrate the difference:
struct foo { void bar() {} void bar1() & {} void bar2() && {} };
Example:
int main() { foo().bar(); // (always fine) foo().bar1(); // doesn't compile because `bar1()` requires an lvalue foo().bar2(); // doesn't compile because `bar2()` requires an rvalue foo f; f.bar(); // (always fine) f.bar1(); f.bar2(); // doesn't compile because `bar2()` requires an rvalue }
The above is the detailed content of What Does the Single Ampersand (&) Mean in a C Member Function Declaration?. For more information, please follow other related articles on the PHP Chinese website!