title: Why do std::function instances have a default constructor?
body: <p>This is probably a philosophical question, but I ran into the following problem:</p>
  
  <p>If you define an std::function, and you don't initialize it correctly, your application will crash, like this:</p>
  
  <pre><code>typedef std::function&lt;void(void)&gt; MyFunctionType;
  MyFunctionType myFunction;
  myFunction();
  </code></pre>
  
  <p>If the function is passed as an argument, like this:</p>
  
  <pre><code>void DoSomething (MyFunctionType myFunction)
     {
     myFunction();
     }
  </code></pre>
  
  <p>Then, of course, it also crashes.  This means that I am forced to add checking code like this:</p>
  
  <pre><code>void DoSomething (MyFunctionType myFunction)
     {
     if (!myFunction) return;
     myFunction();
     }
  </code></pre>
  
  <p>Requiring these checks gives me a flash-back to the old C days, where you also had to check all pointer arguments explicitly:</p>
  
  <pre><code>void DoSomething (Car *car, Person *person)
     {
     if (!car) return;      // In real applications, this would be an assert of course
     if (!person) return;   // In real applications, this would be an assert of course
     ...
     }
  </code></pre>
  
  <p>Luckily, we can use references in C++, which prevents me from writing these checks (assuming that the caller didn't pass the contents of a nullptr to the function:</p>
  
  <pre><code>void DoSomething (Car &amp;car, Person &amp;person)
     {
     // I can assume that car and person are valid
     }
  </code></pre>
  
  <p>So, why do std::function instances have a default constructor?  Without default constructor you wouldn't have to add checks, just like for other, normal arguments of a function.
  And in those 'rare' cases where you want to pass an 'optional' std::function, you can still pass a pointer to it (or use boost::optional).</p>