Search code examples
c++nullreturn-valueshared-ptrdereference

Inconsistency when dereferencing returned empty shared_ptr


I recently noticed some strange behavior when using a returned empty shared_ptr. To illustrate the problem consider this example:

    struct A {
      A() { }
      void foo() {
        std::cout << "A::foo" << std::endl;
      }
    };

    struct B {
      B() :i(42) { }
      void foo() {
        std::cout << "B:foo with i: " << i << std::endl;
      }

      int i;
    };

    template<typename T>
    std::shared_ptr<T> create_empty() {
      return std::shared_ptr<T>(); 
    }

Then calling:

    std::shared_ptr<A> pa(create_empty<A>());
    pa->foo(); // #1: Works fine and prints: "A::foo".

    std::shared_ptr<B> pb(create_empty<B>());
    pb->foo(); // #2: Throws an exception.

Now my question is why call #1 works (I expected to get an exception as well) and if this is the correct behavior how to prevent #1 from working. Am I supposed to check if the return value is empty? Are there some other ways to return null or empty shared_ptr? I'm using MSVC++ 11 if that matters...


Solution

  • The code in both cases dereferences a null pointer. The behavior is undefined, so anything can happen, including things that seem to make sense. Don't try to make sense out of them. Undefined is undefined.