sigil
sigil

Reputation: 825

Why is there no implicit bitwise comparison in C++?

#include <iostream>
using namespace std;

struct S {
    int m_i;
};

int main() {
    S s1;
    // okay - implicit copy constructor
    S s2(s1);

    S s3;
    // okay - implicit copy assignment
    s3 = s1;

    // awkward
    if(s1 == s2)
        cout << "can't be" << endl;

    return 0;
}

This piece does not compile as expected and, given the age of this design decision and the amount of code that (possibly) depends on it, we are stuck with it forever. Still, does anyone have a hunch about the initial reasons behind it?

Upvotes: 2

Views: 64

Answers (2)

alain
alain

Reputation: 12047

It's because of the padding bytes, which are not initialized and can therefore have any value.

For example, if S is defined as follows:

struct S {
    char m_c;
    int m_i;
};

between m_c and m_i, there are padding bytes which could make s1 and s2 compare unequal, even if all members have the same value.

Another reason is that some types may have multiple object representations for the same value.

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234685

If S, say, contains pointers then two instances of S might have the same contents but their pointers might point to different memory (even if the data at those memory locations are identical).

So your scheme will not work in full generality.

Upvotes: 4

Related Questions