Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on predefined meanings for operators

Tags:

c++

In "The C++ programming language", at page 265, the author makes the following statement:

Because of historical accident, the operators = (assignment), & (address-of), and , (sequencing; §6.2.2) have predefined meanings when applied to class objects. These predefined meanings can be made inaccessible to general users by making them private:

Then the following example is given:

class X {
private:
 void operator=(const X&);
 void operator&();
 void operator,(const X&);
 // ...
};

void f(X a, X b)
{
   a = b;  // error: operator= private
   &a;     // error: operator& private
   a,b;    // error: operator, private
}

I can't quite understand what do these "error" comments refer to? Does that mean I should not define a function like f, or that all of the =, &, and , operators should be used according to the default way, and it is not necessary to redefine them?

like image 674
user630983 Avatar asked Aug 31 '11 15:08

user630983


1 Answers

This example simply shows a way to prevent yourself or other developers of the code from using operators, which can be used without having been defined in the class, because they're automatically generated (and have default meanings for the operations they represent).

The author of the example meant, that if you try to assign b to a (in line a = b) it will cause an error, because the assignment operator is private in the class definition.

Similar error occurs in case of address-of in the second line, and the comma operator in the third.

Making default operators/constructors private if you know they're not supposed to be used (or haven't been implemented yet) is good, because one may accidentally use a very frequent operator like assignment or copy-constructor, being unaware that it's default behavior conflicts with the class lifecycle. If such operator or constructor is made private at the very beginning of class design, the compiler will generate a compile-time error instead of performing a potentially dangerous operation without notice if the programmer accidentally uses the method.

Think default assignment operator and member pointer: it will copy the pointer whereas you might want the object to be the owner of data. Then, after someone assigns one object to another without knowing that assignment is not implemented, you will end up with a double free error. Instead of that, if the operator is private, you'll get a nice error and the code will not even compile, and you'll know what's going on.

like image 55
Michał Trybus Avatar answered Oct 26 '22 11:10

Michał Trybus