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