문제

When using the pointer to member operator (->*), what pointer values for the object will invoke undefined behavior?

Specifically, if the member function in question does not access any members and is not virtual are either of the following bad?

  • Null pointers
  • Pointers to objects which have already been deleted

This question is similar but discusses regular member function calls.

To illustrate with code:

#include <iostream>     
using namespace std;     

class Foo {     
public:     
  int member(int a)     
  {     
    return a+1;     
  }     
};     

typedef int (Foo::*FooMemFn)(int);     

int main(int argc, char** argv)     
{     
  FooMemFn funcPtr = &Foo::member;     
  Foo *fStar = 0;     
  Foo *fStar2 = new Foo();     
  delete fStar2;     

  int a1 = (fStar->*funcPtr)(4);  //does this invoke UB?                                                                                                                                                                                                                             
  int a2 = (fStar2->*funcPtr)(5); //what about this?                                                                                                                                                                                                                               

  cout<<"a1: "<<a1<<"  a2: "<<a2<<endl;     

  return 0;     
}

Questions about undefined behavior are questions about the C++ standard, so I am looking for specific references to sections of the C++ standard.

도움이 되었습니까?

해결책

int a1 = (fStar->*funcPtr)(4);  //does this invoke UB?  
int a2 = (fStar2->*funcPtr)(5); //what about this? 

Yes. Both statements invoke UB.
Because they are equivalent to:

fStar->member(4);
fStar2->member(5);

respectively.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top