I'm writing something to allocate objects/memory, and I ran into a problem because C++ seems to forbid moving types that are not trivially_copyable. I assume that sometimes a memory allocator needs to move memory around, and if it does so cannot return direct pointers or direct handles, but indirect pointers or handles to indices that can then be changed when the memory is moved. I'm guessing this is what's done when memory is defragmented/compacted, but how can I move memory when C++ forbids me from memcpying certain objects? For example:
char* buffer = new char[128];
unsigned long long createMyType() {
// Lets say I find space for MyType at offset 28
new (buffer + 28) MyType;
return 28;
}
void destroyMyType(unsigned long long idx)
{
((MyType*)(buffer + idx))->~MyType();
}
int main()
{
}
Now for whatever reason I want to move a certain part of that buffer, to close a gap (or something). I'm pretty sure I can't memcpy the area that has a MyType object, because it's not trivially_copyable and possibly because it's not an implicit lifetime type. How is it that memory is moved around if there is no knowledge of the objects that exist in that memory? I've read that one reason you can't memcpy certain types is because non_trivially_copyable and non standard layout types are not guaranteed to be contiguous in memory. But I don't really understand how it could not be contiguous. If it's possible it's not contiguous how can something like the operating system shift memory around? Can I not fill a buffer with objects and move the memory and expect it to have the same data/objects?