1

Why are both bind versions compiling and working without problems, even though I'm using different parameter types in each call?

  1. version 1 -> parameter foo vs.
  2. version 2 -> parameter address of foo

I'd expected version 1 to produce a compile error...


#include <iostream>
#include <functional>

using namespace std;

class Test   
{   
public:
   bool doSomething(){ std::cout << "xxx"; return true;};   
};

int main() {

Test foo;

// Version 1 using foo
std::function<bool(void)> testFct = std::bind(&Test::doSomething, foo);

// Version 2 using &foo
std::function<bool(void)> testFct2 = std::bind(&Test::doSomething, &foo);

testFct();
testFct2();

return 0;
}
nabulke
  • 11,025
  • 13
  • 65
  • 114

1 Answers1

1
std::function<bool(void)> testFct = std::bind(&Test::doSomething, foo);

This will bind to a copy of foo, and call the function as copy.doSomething(). Beware that this will be wrong if you're expecting the function to be called on foo itself.

std::function<bool(void)> testFct2 = std::bind(&Test::doSomething, &foo);

This will bind to a pointer to foo and call the function as pointer->doSomething(). Beware that this will be wrong if foo has been destroyed before calling the function.

I'd expected version 1 to produce a compile error...

You could disallow this behaviour by making Test uncopyable, if you wanted.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644