0

Sorry I couldn't think of any better title after I encountered the following piece of code while experimenting.

What I don't understand here is how could I call a function of the class using a nullptr in this case.

#include <memory>
#include <iostream>
using namespace std;

class test {
   public:
      void testfunc() {
         cout << "calling test func" << endl;
      }
};

int main () {
   unique_ptr<test> ptr;
   if (ptr == nullptr) {
      cout << "ptr is null" << endl;
   }

   ptr->testfunc();
   return 0;
}

According to me this should just crash because its a nullptr, but it doesn't and work like as if ptr is not a nullptr.

pranavk
  • 1,774
  • 3
  • 17
  • 25
  • 3
    It's bad luck, nothing more. Undefined behavior means that anything can happen, including running as if there was nothing wrong. – Pete Becker Feb 20 '16 at 19:49
  • 1
    Here's what [GCC](http://goo.gl/N5o0oV) can do to it. – chris Feb 20 '16 at 19:54
  • It doesn't use the this ptr, it's the same as test * ptr=0; ptr->testfunc(); undefined but most compilers are OK with it. – QuentinUK Feb 20 '16 at 19:55

0 Answers0