Home >Backend Development >C++ >What's the Difference Between Single and Double Ampersands in C Member Function Declarations?

What's the Difference Between Single and Double Ampersands in C Member Function Declarations?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 13:34:13428browse

What's the Difference Between Single and Double Ampersands in C   Member Function Declarations?

In-depth Interpretation of the Ampersand in Member Function Declarations

In C , non-static member functions can be decorated with ref-qualifiers. These qualifiers specify the reference category of the implicit object parameter that is passed to the function.

Let's explore the two common ref-qualifiers:

  1. Single Ampersand (&): Denotes that the function can be invoked with an lvalue reference to the object.
  2. Double Ampersand (&&): Denotes that the function can be invoked with an rvalue reference to the object.

Without specifying any ref-qualifier, the function can be invoked regardless of the value category of the object.

To illustrate the difference:

struct Foo {
    void bar() {}  // Default: can be invoked with both lvalues and rvalues
    void bar1() & {}  // Can only be invoked with lvalues
    void bar2() && {}  // Can only be invoked with rvalues
};

In the above example:

  • bar() can be invoked on both lvalues (objects) and rvalues (temporary objects).
  • bar1() can only be invoked on lvalues because it requires an lvalue reference to the object.
  • bar2() can only be invoked on rvalues because it requires an rvalue reference to the object.

Here's a live demonstration:

int main() {
    Foo f;
    f.bar();
    f.bar1();
    Foo().bar2();  // Error: bar2 requires an rvalue
}

Understanding these ref-qualifiers allows you to control the access to your member functions based on the reference category of the object they are being invoked on.

The above is the detailed content of What's the Difference Between Single and Double Ampersands in C Member Function Declarations?. 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