What I understand as a typical use of std::function
#include <iostream>
#include <functional>
using namespace std;
class C {
public:
C() { cout << "CREATING" << endl; }
C(const C&) { cout << "COPY C "<< endl; };
C(C&&) { cout << "MOVE C " << endl; };
~C() { cout << "DELETING"<< endl; }
C& operator =(const C&) {
cout << "COPY A " << endl; return *this;
};
C& operator =(C&&) {
cout << "MOVE A" << endl; return *this;
};
void operator ()() const { cout << "CALLING" << endl; }
};
int main(int argc, char *argv[]) {
function<void()> f = C();
f();
return 0;
}
yields following output
CREATING
MOVE C
DELETING
CALLING
DELETING
Apparently, temporary object is created on stack and then moved into function object. If move constructor is not provided, it is copied instead.
Is there a standard way of setting the target without need for a temporary object?