简体   繁体   中英

Member function pointer calls copy constructor?

I'm trying to create a lookup table of member functions in my code, but it seems to be trying to call my copy constructor, which I've blocked by extending an "uncopyable" class. What I have is something like the following.

enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };

class Foo {
  fun1(Bar b){ ... }
  fun2(Bar b){ ... }
  ...
  void (Foo::*lookup_table[NUM_FUNS])(Bar b);
  Foo(){ 
    lookup_table[FUN1_IDX] = &Foo::fun1;
    lookup_table[FUN2_IDX] = &Foo::fun2;
  }

  void doLookup(int fun_num, Bar b) {
    (this->*lookup_table[fun_num])(b);
  }
};

The error is that the '(this->...' line tries to call the copy constructor, which is not visible. Why is it trying to do this, and what do I have to change so it won't?

Make them reference parameters.

enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };

class Foo {
  fun1(Bar &b){ ... }
  fun2(Bar &b){ ... }
  ...
  void (Foo::*lookup_table[NUM_FUNS])(Bar &b);
  Foo(){ 
    lookup_table[FUN1_IDX] = &Foo::fun1;
    lookup_table[FUN2_IDX] = &Foo::fun2;
  }

  void doLookup(int fun_num, Bar &b) {
    (this->*lookup_table[fun_num])(b);
  }
};

In C++, otherwise such plain parameters don't just reference objects, but they are those objects themselves. Making them reference parameters will merely reference what is passed. In this matter, C++ has the same semantics as C (in which you would use pointers for that).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM