6

I was trying to read and understand std::bind when I stumbled on below answer:

Usage of std::bind

I see one statement like below:

auto callback = std::bind(&MyClass::afterCompleteCallback, this, std::placeholders::_1);

I am unable to understand what is the usage of 'this' pointer and when one should make use of it? 'this' pointer means the current object address itself so it would something mean that 'use this object' - if so how can I use the same statement outside the class still having the same meaning?

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
Programmer
  • 8,303
  • 23
  • 78
  • 162
  • 4
    As you provide a pointer to a (probably non-static) _member function_ `&MyClass::afterCompleteCallback`, it cannot be called without an object. Therefore, the object pointer is provided as well: `this`. If you want to construct the `bind` outside of class just insert the pointer to the respecitive object instead of `this`. E.g. for `MyClass myClass;` it should be `&myClass`. – Scheff's Cat Nov 28 '17 at 13:15
  • It works because in C++ pointer->afterCompleteCallback(p1) is the same as MyClass::afterCompleteCallback(pointer, p1); it's just that the compiler doesn't allow it directly. – QuentinUK Aug 07 '21 at 05:28

1 Answers1

11

Inside the class, outside the class, that's not really important to the use of std::bind. A non-static member function must be called with a valid object of the class it is a member of. std::bind considers that object to be the first argument it is given after the callable, plain and simple.

So you can do it as you noted, inside the class, and supply the "current" object as the first bound argument.

Or you can do it outside the class, if the member is accessible, and supply some object (as @Scheff pointed out):

MyClass myClass; 
using namespace std::placeholders;
auto callback = std::bind(&MyClass::afterCompleteCallback, &myClass, _1);

You may even choose not to bind the object at all, and leave a placeholder for that as well:

MyClass myClass; 
using namespace std::placeholders;
auto callback = std::bind(&MyClass::afterCompleteCallback, _1, _2);

callback(myClass, /*Other arg*/);

Also, and despite the fact you tagged . With the changes to lambdas in , there really is no reason to use std::bind anymore.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • Can you please explain what you mean by the last sentence? – Jaa-c Nov 28 '17 at 13:37
  • 1
    @Jaa-c - It'd be far more educational to [watch this lecture](https://www.youtube.com/watch?v=zt7ThwVfap0). If you are unfamiliar with the presenter, it's Stephan T. Lavavej, the maintainer of Micrsoft's standard library implementation. – StoryTeller - Unslander Monica Nov 28 '17 at 13:42