Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

best way to overload =

Status
Not open for further replies.

Leroy1981

Programmer
Jul 22, 2002
46
US
i've seen source code that uses memset to copy the contents
of one 4x4 matrix into another. is this faster than just using the standard = operator?
 
with a struct with no pointers, memcpy will work. In actualality, you dont need one in this situation as this is the default behaviour for a struct.

with a struct with pointers, you will need to redefine how you copy it or you will do a shallow copy.

with a class, always redefine it (in my opinion)

class sample
{
void operator =(sample& s)
{
membervars = s.membervars;

// depending on "type"
memberpointers = new type;
memcpy(memberpointers,s.memberpointers);
// copy constructor
memberpointers = new type(s.memberpointers);
}
}

it is a very basic explanation but it should get you started :) Repost if you run into problems. What you want to be careful of are shallow copies. That is when you have a pointer and you dont allocate new memory for it but instead just set your pointer to the original pointer value. If the old object goes out of scope, you pointer to its memory block still exists BUT that block of memory has been deleted.


Matt

 
If you have a Matrix class, the designer of the class probably overloaded operator= to do the copy; in that case, it's incorrect to use memcpy to copy the matrix and you must use the assignment operator.

If you just have a simple int[4][4], though, you must use memcpy because the assignment operator won't work. It will compile, but you'll end up having two pointers that refer to the same matrix; changing one will also change the other. You never actually made a copy. This is what Zyrenthian means when he says "shallow copy." This is opposed to a "deep copy," which actually does make a duplicate and gets you two separate matrices (and requires memcpy or something similar).
 
in other words you must be aware of what you are actually
copying. pointers or whole structures. what you want to accomplish will determine the type of copying you will do.

I wonder if you are refering to creating a new structure
and individually copying the contents.

in this case the memcpy will sve some lines of code. but
the individual items have to be copied separately sooner or later.

tomcruz.net
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top