Effective C ++ 2e Item9

zhaozj2021-02-11  191

Terms 9. Avoid hidden standard forms of New

Because the name of the internal range declaration hides the same name of the external range, for the inside of the class, respectively

The function f of the two identical names of the global statement, the members of the class hide the global function:

Void f (); // global function

Class x {public: void f (); // member function};

X x;

f (); // call f

X.f (); // call x :: f

This will not be surprising, it will not cause confusion, because calling global functions and member functions always adopting different

Grammatical form. However, if you add an Operator new function with multiple parameters in the class,

It may be shocked.

Class x {public: void f ();

// Operator new parameters Specify a // new-hand (error handling) function static void * Operator new (size_t size, new_handler p);};

void specialerrorhandler (); // Define in other places

X * px1 = new (SpeciaLerrorhandler) x; // call x :: Operator new

X * px2 = new x; // error!

After a function called "Operator New" is defined in the class, it is not intentionally stopped from accessing the standard New.

ask. The clause 50 explains why this is, here we are more concerned about how to think of a way to avoid this problem.

One way is to write an Operator New that supports standard New calls in the class, which is the same as the standard New

Do things. This can be encapsulated with an efficient inline function.

Class x {public: void f ();

Static void * Operator new (size_t size, new_handler p);

Static void * operator new (size_t size) {return :: operator new (size);}}

X * px1 = new (SpeciaLerRhandler) x; // Call x :: operator // new (size_t, new_handler)

X * px2 = new x; // Call x :: Operator // new (size_t)

Another method is to provide default values ​​for each parameter added to Operator New (see Terms 24):

Class x {public: void f ();

Static void * operator new (size_t size, // p default is 0 new_handler p = 0); //};

X * px1 = new (SpeciaLerRhandler) x; // correct

X * px2 = new x; // is also correct

No matter which method, if you want to customize new features in the "standard" form, you only need to override this function.

. The call can use new features after recoiling the link.

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

New Post(0)