Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make a bitwise copy of a C++ object?

Tags:

c++

Can C++ objects be copied using bitwise copy? I mean using memcopy_s? Is there a scenario in which that can go wrong?

like image 692
Mehran Avatar asked Oct 05 '09 22:10

Mehran


People also ask

What is a Bitwise copy?

Bitwise copying is a way to get a copy of a class object by copying every bit (byte) of a particular class object (instance). Bitwise copying is used when it is necessary to obtain an identical destination object from the source object.

Which among the following is Bitwise copy of an object?

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object.

Can we create copy of same object C++?

Copy Constructor in C++A copy constructor is a member function that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.

Which operator is used to copy an object?

Copying of objects is achieved by the use of a copy constructor and an assignment operator. A copy constructor has as its first parameter a (possibly const or volatile) reference to its own class type. It can have more arguments, but the rest must have default values associated with them.


1 Answers

If they're Plain Old Data (POD) types, then this should work. Any class that has instances of other classes inside it will potentially fail, since you're copying them without invoking their copy constructors. The most likely way it will fail is one of their destructors will free some memory, but you've duplicated pointers that point to it, so you then try to use it from one of your copied objects and get a segfault. In short, don't do it unless it's a POD and you're sure it will always be a POD.

like image 176
rmeador Avatar answered Sep 24 '22 06:09

rmeador