2

I have a class A that has a non-const member function foo that must not be called on temporaries, this is how it looks like:

struct A
{
    void foo() &
    {...}
};

If foo were const I would have to explicitly delete the const&& version since const rvalues can bind to const lvalues, in fact the following code compiles just fine

struct A
{
    void const_foo() const &
    {...}

    // void const_foo() const&& = delete;
    // ^^^^ uncomment to prevent calling foo on const rvalues
};

int main()
{
    const A a;
    std::move(a).const_foo();
}

So there's a reason to explicitly delete a const rvalue ref qualified function, are there any reasons also for non-const functions?

user7769147
  • 1,559
  • 9
  • 15
  • What exactly is the reason your `foo()` should not be called on temporaries? – G. Sliepen Jun 07 '20 at 09:18
  • I can’t think of an actual reason, but I would =delete it in any case to make your intent clear. – besc Jun 07 '20 at 09:29
  • @G. Sliepen In my case `foo` does some heavy modifications on internal data members and does not have any side effect, thus calling it on a temporary makes no sense since the object is going to die anyway. A good compiler may optimize out the call but may not warn me. By deleting it instead, the code won't compile and I would understand I'm doing something wrong – user7769147 Jun 07 '20 at 09:50

0 Answers0