4

I'm looking through some internal infrastructure code at the moment and I saw some functions defined as such:

// func_name is a class member function

some_return_type func_name() & {
  // definition
}

some_return_type func_name() && {
  // definition
}

some_return_type func_name() const& {
  // definition
}

some_return_type func_name() const&& {
  // definition
}

I know having const after a class member function name means it won't modify immutable member variables defined in the class. But what does &, &&, const &, and const && variants here mean?

roulette01
  • 1,984
  • 2
  • 13
  • 26
  • @Frank Do you know what the name of this C++ feature is called? I wanted to Google to do some reading on it but not sure what the name is to google for – roulette01 Nov 11 '21 at 02:42
  • Does this answer your question? [What is "rvalue reference for \*this"?](https://stackoverflow.com/questions/8610571/what-is-rvalue-reference-for-this) – 康桓瑋 Nov 11 '21 at 03:04
  • https://stackoverflow.com/questions/21861148/ – M.M Nov 11 '21 at 03:07

1 Answers1

8

Using self as the object the method is called on:

  1. self must match Type&:

    some_return_type func_name() &;
    
  2. self must match Type&& (and will also match Type const&& and Type const&):

    some_return_type func_name() &&;
    
  3. self must match Type const&& (and will also match Type const&):

    some_return_type func_name() const&&;
    
  4. self must match Type const&:

    some_return_type func_name() const&;
    

As you can see, it would be simpler to understand if C++ had had references from the beginning, and chose self-references instead of this-pointers.

Cppreference.com on ref-qualified member-functions.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118