0

I saw code like that.

What this & means and what is the official name of this kind of methods?

struct S{
    int get() const &{
        return 5;
    }
};

int main(){
    S s;
    return s.get();
}
Nick
  • 9,962
  • 4
  • 42
  • 80
  • The `&` is termed as a [reference](https://isocpp.org/wiki/faq/references). – mmcblk1 Jun 27 '21 at 12:44
  • I know what reference is, but no idea what you mean. Can you elaborate? – Nick Jun 27 '21 at 12:47
  • The technical term: the function has a _ref-qualifier_. This is just taken from the C++ grammar, where _ref-qualifier_ is a symbol used to say that `&` or `&&` may appear in that place in a function declarator. – aschepler Jun 27 '21 at 13:09

2 Answers2

2

The const & on the method signature means that the calling object shall be bounded to a const lvalue reference.

However, since rvalue can be bound to a const lvalue ref, the following code would compile:

struct S{
    int get() const &{
        return 5;
    }
};
  

int main(){
    return S{}.get(); // compiles, S{} can be bound to const lvalue
}

To see the actual meaning of the & you can either add a version for && or drop the const:

With an overload for const &&:

struct S{
    int get() const &{
        return 5;
    }
    int get() const && {
        return -5;
    }
};
  
int main(){
    return S{}.get(); // returns -5
}

With & but without const:

struct S{
    int get() & {
        return 5;
    }
};
  
int main(){
    return S{}.get(); // compilation error cannot bind rvalue to lvalue
}
Amir Kirsh
  • 12,564
  • 41
  • 74
1

The const means the function itself is const - it is a compile time error for that function to modify the member data items of the class/struct, and therefore the function can be called using a const reference to an instance of the class.

The trailing & is very unusual (I've never seen one in the wild). It means the reference to the instance that is used to invoke this function must be an lvalue. A function followed by && must be called from an rvalue.

I believe a function can be declared and defined twice, once with & and once with &&, as it forms part of the signature. This is useful for certain obscure optimizations (apparently).

Andy Newman
  • 1,178
  • 2
  • 8
  • 23