title: Ways to store arbitrary data in a std::vector<unsigned char>
body: <p>I have a third party api that provides the following type (approx.) for attaching arbitrary data to a node in a tree structure:</p>
  
  <pre><code>// 3rd party, cannot be modified
  struct AttachedData
  {
      std::string key;
      std::vector&lt;unsigned char&gt; data;
  };
  </code></pre>
  
  <p>I think it uses <code>std::vector&lt;unsigned char&gt;</code> because the data could also be written to the disk, but this doesn't matter in my use case as the data only persists at runtime.</p>
  
  <p>There are objects of different types that must be stored in <code>AttachedData</code> (only one object per instance). Since I need the data only at runtime I didn't bother implementing any type of serialization (mostly because of the unnecessary overhead). I decided to use a variant of all possible types and store a pointer to an instance thereof in <code>AttachedData</code>:</p>
  
  <pre><code>using StorageType = std::variant&lt;EventArgs1, EventArgs2, SomeData /*, ...*/&gt;;
  
  AttachedData&amp; attachedData = api.getAttachedData(targetNode, "some key"); // get the correct container
  auto storage = new StorageType(someDataInstance); // somehow create the variant on the heap
  attachedData.data.resize(sizeof(storage)); // make enough space
  std::memcpy(attachedData.data.data(), &amp;storage, sizeof(storage)); // store the pointer to the variant 
  </code></pre>
  
  <p>On a different place in the code base the data is read and processed:</p>
  
  <pre><code>AttachedData&amp; attachedData = api.getAttachedData(targetNode, "some key"); // get the correct container
  StorageType* storage = nullptr;
  std::memcpy(&amp;storage, attachedData.data.data(), sizeof(storage)); // read the pointer
  
  // process the stored data
  if (auto* args1 = get_if&lt;EventArgs1&gt;(storage))
      // ...
  else if (auto* args2 = get_if&lt;EventArgs2&gt;(storage))
      // ...
  // ...
  
  // clean up
  attachedData.data.clear();
  delete storage;
  </code></pre>
  
  <p>Is there a cleaner or more elegant way to do that? I also thought about using placement new and construct the variant directly in the vector but that would probably cause alignment issues and I don't see any benefits to it either. I think <code>std::variant</code> is a good way to go but I'm open to suggestions in that regard aswell.</p>