0

Trivially copyable objects can be moved in memory by memmove, such as:

struct X { };

int main() {
   static_assert(std::is_trivially_copyable_v<X>);

   X* px1 = (X*)operator new(sizeof(X));
   new(px1) X{};

   X* px2 = (X*)operator new(sizeof(X));
   memmove(px2, px1, sizeof(X));
   px2->~X();

   operator delete(px1);
   operator delete(px2);
}

Live demo: https://wandbox.org/permlink/68d1cqMt6yd8LBR4.

I just wonder whether there are some other mechanisms how to move objects in memory (reallocate them) next to memmove allowed by the C++ Standards.


To make it clear, I am not asking about C++11 move semantics, which does not move anything by itself.

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93
  • `std::move` is NOT such a possibility. – MSalters Jun 21 '18 at 08:31
  • 3
    Alloc new memory block, copy old object into it, free memory of old object. The point of `memmove` is that it supports copying from overlapping regions. So in your example `memmove` could be replaced with `memcpy`. All the "moving" here is just memory copying. – user7860670 Jun 21 '18 at 08:35
  • @VTT So is it safe not to call the (trivial) destructor of the old object if it exists in this case? – Daniel Langr Jun 21 '18 at 08:38
  • You only construct one object so there should be only one destructor invocation. – user7860670 Jun 21 '18 at 08:40

0 Answers0