Reputation: 66965
So.. How can we call something like memcpy(dataCopy, data, length); to copy abstract data T?
Or if abstract T is not safe lets say we know that T is a POD (plain old data, basically a C struct) - is it possible to copy it?
Upvotes: 4
Views: 1468
Reputation: 361582
You cant do that reliably. If it was so easy, possible and reliable, then programmers would not be overloading operator=()
and writing copy-constructor.
If you want to make a copy of your object, then either overload operator=()
, or write copy-constructor, or do both!
Upvotes: 3
Reputation: 36986
This could be dangerous depending on the type of T. If T is a POD type, then everything's all right. Otherwise, I suggest you simply call T's copy constructor (or use a clone pattern if it's not possible).
Upvotes: 0
Reputation: 30979
Do you mean working for some arbitrary C++ type T
? Unless you know that T
is a POD (plain old data, basically a C struct) type, it is not safe to copy objects of type T
with memcpy
. That would prevent T
's copy constructor from running, for example, which might lead to an incorrect copy (trying to memcpy
an std::vector
would not copy the data buffer, for example).
Upvotes: 3