Aussie AI

Assignment Operator Return Type

  • Book Excerpt from "Generative AI in C++"
  • by David Spuler, Ph.D.

Assignment Operator Return Type

The return type of the overloaded assignment operator should usually be a reference type or void. A common mistake is to make it return a class object. Consider the following class declaration:

    class Integer {
        private: int val;
        public:
        Integer operator = (const Integer &x);
        // ...
    };

    Integer Integer::operator = (const Integer &x)
    {
        val = x.val; // copy data
        return *this; // return left operand
    }

This declaration of the assignment operator to return an object permits expressions using the result of assignment, such as:

    Integer x, y, z;
    x = x + (y = z); // embedded assignment
    x = y = z; // multiple assignment

However, it needlessly calls the constructor and destructor for a temporary object, leading to inefficiency, and occasionally to error. The correct declaration of the assignment operator is to return a const reference to Integer. This simply requires an & in the return type declaration, as follows:

    const Integer& Integer::operator = (const Integer &x)
    {
        // ... same as above
    }

Note that const is required because the use of a non-const reference return type is slightly undesirable because it allows the very strange (and probably incorrect) multiple assignment:

    (x = y) = z;

Although the failure to declare the return type as a reference above was a slug, rather than a bug, it can be more dangerous. For a MyString class with dynamic allocation, using a return type of MyString instead of MyString& will cause a temporary object to be created at the return statement, using the copy constructor with “*this” as the argument. If the copy constructor is defined correctly, this is often just an instance of inefficiency, but it may also lead to fatal errors related to temporary objects. If the copy constructor isn't defined correctly, the programmer has an error with an increased level of complexity caused by temporary objects.

Return Type Void: Note that it may be far better simply to declare the return type of the assignment operator as void, rather than a reference type. Although this prohibits embedded assignments in expressions and also multiple assignments, these are poor style anyway and should probably be discouraged. Using return type void is also slightly more efficient because no value need be returned. However, returning the reference type is the more common C++ idiom.

 

Next:

Up: Table of Contents

Buy: Generative AI in C++: Coding Transformers and LLMs

Generative AI in C++ The new AI programming book by Aussie AI co-founders:
  • AI coding in C++
  • Transformer engine speedups
  • LLM models
  • Phone and desktop AI
  • Code examples
  • Research citations

Get your copy from Amazon: Generative AI in C++