THE OBJECT COPYING PROBLEM
Copying is implicit in passing arguments by value to a function. This is not a problem when the argument is of a fundamental type, but for arguments that are objects of a class type, it can be. The overhead arising from copying an object can be considerable, especially when the object is large or owns memory that was allocated dynamically. Copying an object is achieved by calling the class copy constructor, so the efficiency of this function is critical to execution performance. As you saw with the CMessage class, the assignment operator also involves copying an object. However, there are circumstances where such copy operations are not really necessary, and if you can find a way to avoid them in such situations, execution time can be reduced. Rvalue reference parameters are the key to making this possible.
Avoiding Unnecessary Copy Operations
A modified version of the CMessage class from Ex8_05.cpp will provide a basis for seeing how this works. Here’s a version of the class that implements the addition operator:
class CMessage
{
private:
char* pmessage; // Pointer to object text string
public:
// Function to display a message
void ShowIt() const
{
cout << endl << pmessage;
}
// Overloaded addition operator CMessage operator+(const CMessage& aMess) const { cout << "Add operator function called." << endl; size_t len = strlen(pmessage) + strlen(aMess.pmessage) + 1; CMessage message; message.pmessage = new char[len]; strcpy_s(message.pmessage, len, pmessage); ...
Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.