许多主题告诉我们,使用像 lambda 表达式这样的小对象可以避免在使用std::function. 但我的研究表明并非如此。
这是我的实验代码,很简单
#include <iostream>
#include <functional>
using namespace std;
typedef std::function<int(int, int)> FUNC_PROTO;
class Test
{
public:
int Add(int x, int y) { return x + y; }
};
int main()
{
Test test;
FUNC_PROTO functor = [&test](int a, int b) {return test.Add(a, b); };
cout << functor(1, 2) << endl;
}
Run Code Online (Sandbox Code Playgroud)
我在centos7上编译它,gcc版本4.8.5 20150623但是valgrind显示了这一点:
==22903== HEAP SUMMARY:
==22903== in use at exit: 0 bytes in 0 blocks
==22903== total heap usage: 1 allocs, 1 frees, …Run Code Online (Sandbox Code Playgroud)