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;
}
2
  • Becasue you can call a member function on both an object and pointer to an object? Commented Sep 11, 2013 at 11:47
  • 1
    duplicate answers my question Commented Sep 11, 2013 at 11:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.