Why C Compilers Don't Automatically Generate Comparison Operators
Despite the compiler's ability to provide essential methods like default constructors and assignment operators, it notably omits defining comparison operators, such as operator== and operator!=. This omission has raised the question: why?
One argument suggests that if the compiler can generate a default copy constructor, it should also be capable of providing a default operator==(). However, the decision not to do so may stem from the reluctance of Bjarne Stroustrup, C 's creator, to include default copying mechanisms.
In his book "The Design and Evolution of C ," Stroustrup expresses his disapproval of default copy operations, stating that he often prohibits copying in his own classes. This reluctance stems from the fact that default copy constructors were inherited from C and are frequently abused.
Thus, instead of questioning why C lacks a default operator==(), it is more pertinent to consider why it includes default assignment and copy constructors. This decision was made out of backward compatibility with C, which has been both a blessing and a begrudging compromise in C 's evolution.
For those who prefer to prevent default copy operations, declaring private assignment operators and copy constructors in their IDE snippets may be a useful practice. This allows for explicit removal of these declarations when desired, ensuring greater control over class behavior.
The above is the detailed content of Why Don\'t C Compilers Automatically Generate Comparison Operators?. For more information, please follow other related articles on the PHP Chinese website!