title: Shared pointers and queues in FreeRTOS
body: <p>A C++ wapper around a FreeRTOS queue can be simplified into something like this:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>template&lt;typename T&gt;
  class Queue&lt;T&gt;
  {
      public:
      bool push(const T&amp; item)
      {
          return xQueueSendToBack(handle, &amp;item, 0) == pdTRUE;
      }
  
      bool pop(T&amp; target)
      {
          return xQueueReceive(handle, &amp;target, 0) == pdTRUE;
      }
      private:
      QueueHandle_t handle;
  }
  </code></pre>
  
  <p>The documentation of <code>xQueueSendToBack</code> states:</p>
  
  <p><code>
  The item is queued by copy, not by reference.
  </code></p>
  
  <p>Unfortunately, it is <strong>literally</strong> by copy, because it all ends in a <code>memcpy</code>, which makes sense since it is a C API. While this works well for plain old data, more complex items such as the following event message give serious problems.</p>
  
  <pre class="lang-cpp prettyprint-override"><code>class ConnectionStatusEvent
  {
      public:
          ConnectionStatusEvent() = default;
          ConnectionStatusEvent(std::shared_ptr&lt;ISocket&gt; sock)
              : sock(sock)
                {
                }
  
                const std::shared_ptr&lt;ISocket&gt;&amp; get_socket() const
                {
                    return sock;
                }
  
      private:
          const std::shared_ptr&lt;ISocket&gt; sock;
          bool connected;
  };
  </code></pre>
  
  <p>The problem is obviously the <code>std::shared_ptr</code> which doesn't work at all with a <code>memcpy</code> since its copy constructor/assignment operator isn't called when copied onto the queue, resulting in premature deletion of the held object when the event message, and thus the shared_ptr, goes out of scope.</p>
  
  <p>I could solve this by using dynamically allocated <code>T</code>-instances and change the queues to only contain pointers to the instance, but I'd rather not do that since this shall run on an embedded system and I very much want to keep the memory static at run-time.</p>
  
  <p>My current plan is to change the queue to contain pointers to a locally held memory area in the wrapper class in which I can implement full C++ object-copy, but as I'd also need to protect that memory area against multiple thread access, it essentially defeats the already thread-safe implementation of the FreeRTOS queues (which surely are more efficient than any implementation I can write myself) I might as well skip them entirely.</p>
  
  <p><strong>Finally, the question:</strong></p>
  
  <p>Before I implement my own queue, are there any tricks I can use to make the FreeRTOS queues function with C++ object instances, in particular <code>std::shared_ptr</code>?</p>