Memcpy and C ++ class templates - how to use it?

So ... As we can call something like memcpy (dataCopy, data, length); to copy abstract data T?

Or, if abstract T is unsafe, let's say we know that T is POD (plain old data, mostly C struct) - can it be copied?

+4
source share
3 answers

Do you mean working on some C ++ type T ? If you do not know that T is POD (plain old data, mainly type C struct), it is not safe to copy objects of type T with memcpy . This will prevent the T copy constructor from starting, for example, which can lead to an incorrect copy (for example, memcpy a std::vector does not copy the data buffer).

+3
source

You cannot do it reliably. If it were so simple, possible and reliable, then the programmers did not overload operator=() and write copy-constructor.

If you want to make a copy of your object, either overload operator=() , either write copy-constructor, or do both!

+3
source

This can be dangerous depending on type T. If T is type POD, then everything is fine. Otherwise, I suggest that you simply call the T-copy constructor (or use the cloning pattern if this is not possible).

0
source

Source: https://habr.com/ru/post/1336645/


All Articles