title: Null pattern with QObject
body: <p>(C++/Qt) I have a smart pointer to a QObject. Let's say a QWeakPointer. For some external reason (something that might happen in another object or due to an event), it is possible that the pointed object gets destroyed. Since I have a smart pointer there will be no dangling reference, so there's no problem. But I always have to check if the pointer is null or not.</p>
  
  <p>I'm thinking of using the null pattern in order to avoid checking this all the time but I'm not sure if this is possible or convenient with a QObject. The idea would be that the pointer points to the object and in case it gets destroyed, the smart pointer changes its pointed object to a null object. Is this a good idea or should I forget it and just check if the pointer is NULL all the time?</p>
  
  <hr>
  
  <p>Let's show you an example. We have a worker who uses a tool to do its work:</p>
  
  <pre><code>class Worker : public QObject
  {
      Q_OBJECT
  
  public:
      Worker(QObject *parent = 0);
      void work()
      {
          if(m_tool)
              m_tool-&gt;use();
          emit workCompleted();
      };
  
  signals:
      workCompleted();
  
  public slots:
      void setTool(QWeakPointer&lt;Tool&gt; tool);
  
  private:
      QWeakPointer&lt;Tool&gt; m_tool;
  };
  
  
  class Tool : public QObject
  {
      Q_OBJECT
  
  public:
      Tool();
  
  public slots:
      void use() =0;
  };
  
  
  class Screwdriver : public Tool
  {
      Q_OBJECT
  
  public:
      Screwdriver() : Tool();
  
  public slots:
      void use()
      {
          // do something
      };
  };
  
  
  class Hammer : public Tool;
  class Saw : public Tool;
  ...
  </code></pre>
  
  <p>In this case, the Tool is a public domain object of a library, which is used by the Worker. I'm developing such library. So the worker is using a screwdriver but it gets broken and gets destroyed. No problem:</p>
  
  <pre><code>if(m_tool)
      m_tool-&gt;use();
  emit workCompleted();
  </code></pre>
  
  <p>m_tool is 0 so it simply does nothing. But we have to check that it's not null everytime.</p>
  
  <p>Now let's say we had a NullTool object:</p>
  
  <pre><code>class NullTool : public Tool
  {
      Q_OBJECT
  
  public:
      NullTool() : Tool();
  
  public slots:
      void use()
      {
          // does nothing
      };
  };
  </code></pre>
  
  <p>When the tool was destroyed, our pointer would be smart and would know it should point to a NullTool instance. So Worker::work() could be implemented like this:</p>
  
  <pre><code>void Worker::work()
  {
      m_tool-&gt;use();
      emit workCompleted();
  };
  </code></pre>
  
  <p>m_tool->use() would then get called on the NullTool which does nothing, so there would be no need to check the pointer is not null.</p>
  
  <p>Is this a good idea? Is it possible with the smart pointer classes Qt provides or should I subclass QWeakPointer?</p>