Perhaps it is a question that would fit better on a site like stackoverflow but let’s give it a shot…
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:
all objects are constructed using placement-new in a memory that was previously malloc’ed
after moving an object from location A to location B the destructor on A is never called and the memory is just free’d
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?
@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.