A question for C++ experts...

Perhaps it is a question that would fit better on a site like stackoverflow but let’s give it a shot… :slight_smile:
Posting it in this section because it’s a general C++ question and it doesn’t relate directly to UE4 or gameplay programming. Please move it to a more appropriate location if necessary.

Simply, the question is: is it legal to copy a C++ object using memmove/memcpy?

I am aware that it is generally a bad idea that might lead to a number of problems. Here’s what I am doing though:

  1. all objects are constructed using placement-new in a memory that was previously malloc’ed
  2. after moving an object from location A to location B the destructor on A is never called and the memory is just free’d
  3. all the shady operations are well-encapsulated so there should be no external pointers

So, the main question here is: does the Standard guarantee that after memcpy’ing an object from location A to location B the new object at the location B is still a valid object?

Thanks in advance!

Not an expert, so I can’t really answer the question. But may I ask: Why don’t you use copy/move constructors?

@TriNityGER
I am trying to avoid calling copy constructors because of performance. Imagine a class that would allocate/copy memory when copied (say, a dynamic array).

Move constructors… Well to be honest I still don’t know much about them. Can they be called explicitly? Can they be used with a placement new? And another potential source of issues is the fact that I am writing a template class that potentially can be used with legacy classes that don’t have move constructors defined. Would it become an issue? Idk…

Using memcpy/memmove with classes is valid as long as class meet requirements of is_trivially_copyable. (AFAIK some implementations of std::copy use it to choose most optimal way)
Like TriNityGER say, you can use move constructors/move assignment operators. Much safer option than pure memcpy.

There are many ways to solve performance issues due to copy constructors. One way is to load them all via separate thread, or time-slicing. But without further details, suggestions are quite impossible.

Move constructors do pretty much exactly what you described.