#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
作爲庫用戶的回調。std :: bind結構構建std :: function時出現堆棧溢出
我想要類似f4
來簡化回調函數。我不熟悉std::bind
內部。
爲什麼f3
無法構造f4
?
我使用
鐺++:蘋果LLVM 5.0版(鐺 - 500.2.79)(基於LLVM 3.3svn)
上OSX10.9的MacBook編譯:
鐺++ -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
運行時間堆棧溢出或編譯時間?什麼編譯器,什麼版本? – Yakk
如果你省略了bind表達式locals,比如直接將'std :: bind'的結果賦值給'std :: function'變量,它會發生嗎? –
在clang ++ 3.4和g ++ 4.8.1上生成預期結果(沒有堆棧溢出) – dyp