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();
}
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();
}
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
}
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).