Why can a member function be called temporarily, but a global function cannot?

In the code below, I call stepas a member function and as a global function in a temporary value. The member function is enabled and running, while the global function is disabled due to invalid initialisation of non-const reference of type ‘kludge&’ from an rvalue of type ‘kludge’.

I am trying to understand from a language point of view why one behavior is allowed and the other is not. Technically, both calls and functions seem like they will be compiled the same way, or at least they can be.

#include <iostream>

struct kludge {
    int a;
    kludge() {
        a = 1;
    }

    kludge & step() {
        a++;
        std::cout << a << ",";
        return *this;
    }
};

kludge get() {
    kludge t;
    return t;
}

kludge & step( kludge & t ) {
    t.a++;
    std::cout << t.a << ",";
    return t;
}

int main() {
    get().step();
    step( get() );
}
+4
source share
2 answers

r lvalue- 1. step(get()), step, , prvalue ( r) get().

, - : lvalue rvalue - [over.match.funcs]/4 /5:

-

  • "lvalue reference to cv X" , ref- & ref-qualifier

[..]

-, ref-, :

  • , const -qualified, r , . [. , rvalue (13.3.3.2). - ]

ref-qualifiers, , -. , :

kludge & step() & { /* .. */ }

get().step() .


1)
, [dcl.init.ref]/5, :

"cv1 T1" "cv2 T2" :

  • lvalue
    • lvalue [..]
    • (.. T2 - ), T1 T2 lvalue "cv3 T3", [..]

  • lvalue const (.. cv1 const), rvalue.
+6

step( get() );
//    ~~~~~   Creates a temporary object (r-value)
// But step( ) excepts a non-const reference
+1

Source: https://habr.com/ru/post/1569215/


All Articles