title: C++ How should I return my byte array?
body: <p>I've got a class named X (e.g.) and a public function toBytes() which returns some custom binary representation of the object. </p>
  
  <p>My problem is: how should I return this byte array?</p>
  
  <p>Currently, I have this:</p>
  
  <pre><code>uint8_t* X::toBytes()
  {
      uint8_t* binData = new uint8_t[...];
  
      // initialize the byte array
  
      return binData;
  }
  </code></pre>
  
  <p>The problem (or as problem considered by me as an inexperienced c++ programmer) here is that it's allocating the memory on the heap and should be freed at some point which I don't think is practical. Either the class X should free this memory in its destructor in some cumbersome way or the caller should free it. How is the caller supposed to know it is responsible for freeing the memory? It doesn't even know if it's heap memory, right?</p>
  
  <p>Kinda stuck here :/</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I just thought of a possible solution: let the caller supply the memory as in a pointer to a byte array and initialize that array. This would solve the problem, right?</p>