Rella
Rella

Reputation: 66965

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

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

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

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

Etienne de Martel
Etienne de Martel

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

Jeremiah Willcock
Jeremiah Willcock

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

Related Questions