对于什么对象指针值,指向成员操作符的指针是否调用未定义的行为?

时间:2012-07-18 03:02:46

标签: c++ undefined-behavior standards-compliance pointer-to-member

当使用指向成员运算符的指针( - > *)时,对象的哪些指针值将调用未定义的行为?

具体来说,如果有问题的成员函数没有访问任何成员而且不是虚拟的,那么下列任何一个都不好?

  • 空指针
  • 指向已删除对象的指针

This question类似,但讨论了常规成员函数调用。

用代码说明:

#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;     
}

关于未定义行为的问题是关于C ++标准的问题,所以我正在寻找对C ++标准部分的具体引用。

1 个答案:

答案 0 :(得分:1)

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

是。 两个语句都会调用UB 因为它们相当于:

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

分别