mercredi 2 septembre 2015

Why "move semantics" rather than simply memcpy?

Given the following code:

typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_t;

//this moves the back of src to the back of dst:
void push_popped(std::list<storage_t> & dstLst, std::list<storage_t> & srcLst)
{
  auto & src = srcLst.back();
  dstLst.push_back(storage_t());
  auto & dst = dstLst.back();
  std::memcpy(&dst, &src, sizeof(T));
  srcLst.pop_back();
}

I'm aware of 3 reasons why this approach is not, in general, correct (even though it avoids calling src->~T() and so avoids double-reclamation of T's resources).

  1. class member pointers that point to other class members
  2. hidden class members may need to be updated (vtable, for instance)
  3. the system needs to record that no T exists anymore at src and that a T does now exist at dst

(These are mentioned here: http://ift.tt/1IIOMCz.)

Assuming that T is not a type whose memory address is a property of its state (std::mutex or std::condition_variable, for instance), are these the only issues with this approach? Or are there other things that could go wrong? I'd like a description of the unknown issues.

I'd like to think I have an "object relocation semantics" developed, but I'd rather not ask people to consider it if there's an obvious hole in it.

Aucun commentaire:

Enregistrer un commentaire