Dann Corbit wrote:Robert Pope wrote:sje wrote:Since source and destination objects are both structs of the same type, why not use a direct assignment instead of
memcpy()?
Does that work? I thought you could only do that with the simple types, like int.
If you have pointers to objects in your struct, then you might have problems due to shallow copy.
Do a web search for shallow copy deep copy if you are not sure what I mean.
Objects (i.e., struct/class instances) can be divided into lightweight and heavyweight categories. A lightweight object can be copied with
memcpy() or with a direct assignment, and everything should work. A heavyweight object will have at least one pointer to a dynamically allocated other object, and a simple copy might not work if later the same referenced object is deallocated twice.
Copying heavyweight objects is handled in C++ by means of what's called a
copy constructor, a routine also known as a
c'tor. The
c'tor knows how to duplicate referenced objects as needed and even knows not to try and copy an object onto itself. Also in C++ is the struct/class
destructor routine (or
d'tor) which properly terminates an object, releasing allocated references as needed. Nearly all of the time the
c'tor and
d'tor routines are called automatically as needed.
A good C++ reference manual, much used by me:
http://www.cplusplus.com/
----
And now for a programming trick of sorts. In
Symbolic, the
Position class is heavyweight, as are several of its components (various lists). Its copy constructor works by copying the simple stuff directly and using the copy constructors of its heavyweight components.
One of the
Position methods is the
Flip() routine which flips not only the colors and board of the position, but also the position's total move history, status lists, signatures, etc. A lot of work, but simply done because one of the
Position members is the
ifen string, the FEN of the
Position instance initial set up. A
Flip() works by creating a new
Position instance using the flipped
ifen string, and then playing all of the flipped moves from the source position's history.