#include <stdio.h>
#include <functional>
void foo(int a, int b)
{
printf("%d %d\n", a, b);
}
int main()
{
using namespace std::placeholders;
auto f1 = std::bind(foo, 10, _1); // fine
std::function<void (int)> f2 = f1; // fine
auto f3 = std::bind(f2, 20); // fine
std::function<void ()> f4 = f3; // stack overflow
std::function<void ()> f5 = [=](){f3();}; // stack overflow
f3();
return 0;
}
我正在编写一个简单的库并std::function
用作库用户的回调。
我想要一些类似f4
简化回调函数的东西。
我对std::bind
内部不熟悉。
为什么f3
不能构造f4
?
我在用
clang++ : Apple LLVM 5.0 (clang-500.2.79) (基于 LLVM 3.3svn)
在 OSX10.9 macbook 上
编译:
clang++ -g -std=c++0x test.cpp
f4 处的堆栈溢出,因为流动的东西的无限调用:
frame #0:
frame #1:
...
frame #6361: 0x0000000100001ff2 a.out`std::__1::function<void ()>::function<std::__1::__bind<std::__1::function<void (int)>&, int> >(std::__1::__bind<std::__1::function<void (int)>&, int>, std::__1::enable_if<__callable<std::__1::__bind<std::__1::function<void (int)>&, int> >::value, void>::type*) [inlined] std::__1::unique_ptr<std::__1::__function::__base<void (this=0x00007fff5fbfeb00, this=0x0000000100103a90, __f=0x00007fff5fbff4e0, __a=0x00007fff5fbfeae8)>, std::__1::__allocator_destructor<std::__1::allocator<std::__1::__function::__func<std::__1::__bind<std::__1::function<void (int)>&, int>, std::__1::allocator<std::__1::__bind<std::__1::function<void (int)>&, int> >, void ()> > > >::get() const + 42 at functional:1007
frame #6362: 0x0000000100001fc8 a.out`std::__1::function<void (this=0x00007fff5fbff530, __f=0x00007fff5fbff4e0, =0x0000000000000000)>::function<std::__1::__bind<std::__1::function<void (int)>&, int> >(std::__1::__bind<std::__1::function<void (int)>&, int>, std::__1::enable_if<__callable<std::__1::__bind<std::__1::function<void (int)>&, int> >::value, void>::type*) + 776 at functional:1285
frame #6363: 0x0000000100001a3d a.out`std::__1::function<void (this=0x00007fff5fbff530, __f=<unavailable>, =0x0000000000000000)>::function<std::__1::__bind<std::__1::function<void (int)>&, int> >(std::__1::__bind<std::__1::function<void (int)>&, int>, std::__1::enable_if<__callable<std::__1::__bind<std::__1::function<void (int)>&, int> >::value, void>::type*) + 29 at functional:1289
frame #6364: 0x000000010000189c a.out`main + 956 at test.cpp:15