const &, const &&, &, && after a function?

Viewed 234

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?

1 Answers

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.

Related