I'm having trouble understanding some subtleties when combining std::bind with std::function.
I have minimized my problems to the following code snippet:
#include <functional>
#include <iostream>
void bar(int x) {
std::cout << "Hello." << std::endl;
}
int main(int argc, char* argv[])
{
std::function<void(int)> f1 = std::bind(bar, std::placeholders::_1);
// CRASHES with clang, works fine in VS2010 and VS2012
std::function<void()> f2 = std::bind(f1, 1);
f2();
return 0;
}
Note the explicit conversion to std::function<> (replacing std::function<void()>
with auto
when constructing f2
works fine).
Creating f2
by copying the f1
object crashes with Clang on OS X (XCode 5.0.1, OS X 10.9 SDK), but works fine with VS2010/VS2012. After a hideously long callstack, the code crashes with a EXC_BAD_ACCESS - note this is when constructing the function object, not when calling it.
Is this a bug in the library implementation or a problem with my code?
A workaround is to explicitly call the operator ()
member, like this:
std::function<void()> f2 =
std::bind(&std::function<void(int)>::operator(), f1, 1);
but this comes with a caveat, as it fails to compile on VS2012 (but works in VS2010). This seems to be a bug with VS2012.
Your code works just fine with clang 3.4 (trunk, 194324). It also works with gcc 4.7.2.
I don't get any warnings with -Wall -Wextra -pedantic
(except those that complain about the unused x, argc and argv parameters).
It seems as if the clang implementation was buggy in the past but has been fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With