Choosing a copy constructor

As we said, and as you saw in the code examples above, we didn't use copy constructors in any of the component Clone methods. We also didn't use them in the Clone method of M5Object. By default, classes have copy constructors and assignment operators generated by the compiler. In the Shape example above, we used the compiler generated copy constructor in our Clone methods.

However, in the Mach5 Engine there is an important choice to consider. What should the copy constructor do about the m_id variable value? Remember that this ID is supposed to be unique for every object and every component. However, if we use the compiler generated copy constructor, each variable, including m_id, will be copied by value. This would mean that any time we use the copy constructor, we would have two objects with the exact same ID.

Sometimes this is what we want, such as if we wanted to have a vector of objects instead of pointers to objects, for example. When using standard vectors (and other containers), the copy constructor gets called when adding to the container. If we were to add an object, we probably would want it to copy the ID. It is also possible that we would want to shift the position of the object around the container. Most likely, we would want it to keep the same ID.

However, this is not the behavior we want in our Clone methods. We want each clone to be a separate entity with a different unique ID. Of course, we could write our own copy constructor and give a different ID to each newly created object or component, just as we do in the default constructors. Unfortunately, if we did that using standard containers we would be generating new IDs for every time they internally called the copy constructor. In this case, the IDs wouldn't match up to the correct objects or components.

In the Mach5 Engine we use containers of pointers instead of containers of objects or components, so the authors decided to remove the copy constructors (and assignment operators) all together. This will remove all confusion about the process. If you want a copy, you call the Clone method, because you can't call the copy constructor. It is fine to make a different decision. In a different engine that uses containers of objects instead of pointers, a different decision would probably be made.

In the Mach5 Engine, we remove these methods from the object by making them private so that they can't be called. In C++ 11, you can mark them as deleted so the compiler won't generate them for you. The assignment operators will already be removed because these classes contain const data that can't be reassigned:

//In M5Object.h 
M5Object(const M5Object& rhs) = delete;

//In M5Component.h
M5Component(const M5Component& rhs) = delete;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.197.10