title: A packet reader Qt/C++ API design
body: <p>I have a binary packet format which I must implement a C++ reader for. The library uses Qt 4, and the packet source could be any QIODevice, for example, QTcpSocket, QFile or QBuffer. The format includes the packet format, and each packet may also have a lot of sub-structures inside. I need the reader to return the following:</p>
  
  <ul>
  <li>the packet header;</li>
  <li>the array of sub-structures;</li>
  <li>the error status of a read operation - success, an error, or not enough data (particularly when reading from a socket or another sort of buffering device).</li>
  </ul>
  
  <p>There are various possible approaches to the reader API:</p>
  
  <ol>
  <li><code>Packet read(Status &amp;status);</code> - return by value, and return the error status through the reference argument.</li>
  <li><code>Packet *read(bool *ok);</code> - return NULL on error or if not enough data, write true or false to the <code>ok</code> variable (if not NULL) depending on that.</li>
  <li><code>Packet *read();</code> - return NULL on error or if not enough data, call another method <code>bool wasError();</code> to check what happened. This one could be merged with the previous one by making the <code>ok</code> parameter have the default value of <code>NULL</code>.</li>
  <li><code>Status read(Packet &amp;packet);</code> - if the returned status is <code>Ok</code>, the read value is placed into the <code>packet</code> variable, otherwise it indicates either an error or EOF.</li>
  <li><code>Packet read();</code> - return by value, in case of EOF or error return a special "null packet" value. Call <code>wasError()</code> to determine what happened.</li>
  </ol>
  
  <p>There are other possible combinations, of course. There doesn't seem to be the best choice. The approaches 1, 2 and 4 require the caller to declare a separate variable to store the result. The approaches 2 and 3 involve messing with the heap, which I don't want to do for obvious reasons. The approach 1 doesn't make it clear what is returned in case of error. The approach 5 fixes that, but introduces a special "null" flag into the packet structure, although it probably doesn't belong there.</p>
  
  <p>I could take the 5th approach, but return a special structure containing a packet and the status info, but that introduces another "synthetic" type and still leaves open the question "What will the packet field contain in case of an error?"</p>
  
  <p>Or I could take the 3rd approach and return a <code>QSharedPointer&lt;Packet&gt;</code> instead, so the caller doesn't have to mess with heap manually. But the <code>Packet</code> structure will probably already be a kind of smart pointer (a shared class) for the sake of the Pimpl. Maybe I can use that internal pointer instead and introduce an <code>isNull()</code> method, like QString does.</p>
  
  <p>Is there a better, or traditional way of doing it?</p>