Home >Backend Development >C++ >What Does the Single Ampersand (&) Mean in a C Member Function Declaration?

What Does the Single Ampersand (&) Mean in a C Member Function Declaration?

Susan Sarandon
Susan SarandonOriginal
2024-12-15 11:55:09753browse

What Does the Single Ampersand (&) Mean in a C   Member Function Declaration?

Understanding the Single Ampersand in Member Function Declaration

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() && {}
};
  • bar() accepts both lvalues and rvalues.
  • bar1() requires an lvalue reference, so it can only be invoked on lvalue objects.
  • bar2() requires an rvalue reference, so it can only be invoked on rvalue objects.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn