Search code examples
c++operatorsxorostream

XOR operator with std::ostream operator


I wrote a class which represent Qubit. So object has only one value, state, with 0 or 1 (bool). To make needed calculations I overloaded operators like +,*,^. It seems that everything is ok with + and *, also with ^, but only if I won't use it with std::ostream operator.

Qubit x5, x6;
cout << x5^x6; !ERROR!

but with

Qubit x5, x6;
Qubit z = x5^x6;
cout << z;

it's working. My std:operator

std::ostream & operator <<(std::ostream & os, const Qubit & qubit)
{
    os << qubit.GetState();
    return os;
}

and my XOR operator

Qubit & Qubit::operator ^(const Qubit & qubit)
{
    Qubit *q = new Qubit;
    ((this->state == 1 && qubit.state == 0) ||
        (this->state == 0 && qubit.state == 1)) ? q->SetState(1) : q->SetState(0);
    return *q;
}

Solution

  • cout << x5 ^ x6 is evaluated as (cout << x5) ^ x6 due to operator precedence.

    Since you have not provided an overloaded XOR operator for an ostream& and a Qubit (or const Qubit& etc.), compilation fails.

    The solution is to write cout << (x5 ^ x6);

    (Note that the + and * operators have higher precedence than << which is why they work as you describe).

    Finally, you have a serious memory leak in the XOR operator (who is going to delete the allocated memory?). Fix that by changing the function to return a value copy:

    Qubit Qubit::operator^(const Qubit& qubit) const

    and use Qubit q; in the function body. Named Return Value Optimisation will obviate a value copy. For more details, see http://en.cppreference.com/w/cpp/language/operator_arithmetic