vendredi 17 janvier 2020

What is a safe way to pass the this pointer to another function?

I have defined a class that holds a reference to a list of static functions which are defined outside of the class. These functions each take a pointer to that particular instance of the class as a argument.

I'm passing the this pointer to the functions. But that doesn't seem right to me.

Is there a better way?

The code below is a simplified version:

#include <iostream>
#include <map>

class A
{
    public:
       typedef void (*action_func)(A*);
       typedef std::map<int, action_func> func_map;

       A(func_map the_map)
       :m_map(the_map)
       {}

       void execute_action(int action_id)
       {
          auto it = m_map.find(action_id);
          if(it != m_map.end())
          {
             auto cmd = it->second;
             cmd(this);
          }
       }

    private:
       func_map&  m_map;
};


static void function_1(A* ptrToA)
{
    std::cout << "This is function_1\n";
}

static void function_2(A* ptrToA)
{
    std::cout << "This is function_2\n";
}


static A::func_map functions =
{
    {1, function_1},
    {2, function_2}
};


int main()
{
   A obj(functions);
   obj.execute_action(1);
   obj.execute_action(2);
   return 0;
}

The output of the above is this:

This is function_1
This is function_2

Aucun commentaire:

Enregistrer un commentaire