Effective C ++ 2e Item27

zhaozj2021-02-11  237

Terms 27: If you don't want to use a function of implicitly generated, it will be explicitly banned.

Suppose wants to write a class template Array, which is generated, except that the upper and lower limit checks can be performed, in addition to the upper and lower limit checks. One problem facing in the design is how to disable the assignment operation between the Array object, because assigning the standard C array to be illegal:

Double Values1 [10]; Double VALUES2 [10];

VALUES1 = VALUES2; / / Error!

This is not a problem for a lot of functions. If you don't want to use a function, you only use it simply to put it into the class. However, the assignment operator belongs to the unique member function. When you don't write this function, C will write one (see Terms 45). Then what should be done?

The method is to declare this function (Operator =) and make it private. Explicitly declare a member function, prevent the compiler from automatically generating its version; make functions to private, prevent others from calling it.

However, this method is not very safe, member functions and friend functions can also call private functions unless you are smart enough - do not define (implement) this function. This way, when this function is invisible, the program will report an error in the link.

For Array, the definition of the template can be started like this:

Template Class Array {private: // Do not define this function! Array & Operator = (Const Array & RHS);

...

}

Now, when the user tries to perform assignment operations for the Array object, the compiler will not agree; when you are inadvertently call it in a member or friend function, the linker will call it.

Don't think that this Terfeter is only applicable to assignment operators because this example is. not like this. It applies to the function of automatically generated by each compiler described in Terms 45. In practical applications, you will find that assignment and copy constructor has behavioral similarities (see clauses 11 and 16), which means that almost whenever you want to prohibit one of them, it will also prohibit another one.

转载请注明原文地址:https://www.9cbs.com/read-4452.html

New Post(0)