0

For the following code:

class C
{
public:
    void fun() const {};
    void fun() const & {};
};

I know that this is illegal, since we cannot overload with const and const &. However, my question is: we already have const member function in the old standard, why did we need to introduce the const & member function? Are there any semantic differences between a const member function and a const-ref member function?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Wei Li
  • 1,847
  • 2
  • 10
  • 10

1 Answers1

1

What's the difference between const member function and const-ref member function

Lvalue ref qualified function cannot be called on rvalue instance arguments (unless the function is also const qualified). Unqualified member functions can be.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 1
    Don't understand. I tried to call both version with rvalue instance, it seems all versions work: https://godbolt.org/z/9rG3ox and https://godbolt.org/z/rahrze – Wei Li Dec 15 '20 at 23:59
  • Just like you can call const qualified member function through non-const objects, you can call const-ref qualified function through rvalue "objects". You can't however call an rvalue-reference (void f() &&) qualified member function using an lvalue. The lvalue-ref qualified version can be useful if you want to have two versions of the same function: one that would be called when the object is a lvalue, and one that is called when the object is an rvalue – ALEJANDRO PEREZ MORENO Dec 16 '20 at 02:06
  • @WeiLi Sure, but try modifying a non-mutable member variable in const qualified function. That is not possible, while it is possible in a non-const lvalue ref qualified function. Likewise, try calling a const qualified non-lvalue ref qualified function on an rvalue. You'll find that it is possible. – eerorika Dec 16 '20 at 09:18