无法理解该程序的输出

时间:2018-09-15 22:20:50

标签: c++

#include <iostream>
using namespace std;

class A{
  private : static A *ob;
  public : static A* fun1();

  public : void show(string str){
     cout<<"This is :- "<<str<<endl;
  }
};

A* A::ob=NULL;

A* A::fun1(){
  if(ob==NULL){
     ob=new A();
     return ob;
  }
  return NULL;
}


int main() {
   A *ob1 = A::fun1();
   A *ob2 = A::fun1();

   ob1->show("A");    // line 1

   ob2->show("B");   //line 2

   return 0;
}

输出为:-

This is :- A
This is :- B

尽管我只期望“ This is:-A”,因为“ ob2”为NULL,因此取消引用它会产生错误。

有人可以解释输出吗?

1 个答案:

答案 0 :(得分:3)

取消引用NULL是未定义的行为(Why dereferencing a null pointer is undefined behaviour?),通过NULL调用非静态成员函数也是如此:When does invoking a member function on a null instance result in undefined behavior?

这意味着您不能依靠任何行为,甚至不能崩溃。在许多平台上,它将崩溃,但是您描述的输出同样有效。

相关问题