【发布时间】:2015-01-14 22:06:29
【问题描述】:
我理解的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;
}
产生以下输出
CREATING
MOVE C
DELETING
CALLING
DELETING
显然,临时对象是在堆栈上创建的,然后移动到函数对象中。如果未提供移动构造函数,则改为复制它。
是否有无需临时对象即可设置目标的标准方法?
【问题讨论】:
标签: c++ c++11 std-function