C ++ Gotchas Terms 63: MEMBER NEW and MEMBER DELETE The Confusion of Activity Space

zhaozj2021-02-08  461

Gotcha # 63: confusing scope and activation of member new and delete

Gotcha Terms 63: MEMBER New and MEMBER Delete's Confusion and Activity Space

When a category object is created and destroyed, the Member Operator New and Member Operator delete it declared will be evoked. The actual survival space (scope) where the assigned expression is not related to this:

Class string {

PUBLIC:

Void * Operator new (size_t); // Member Operator New

Void Operator Delete (Void *); // Member Operator Delete

Void * operator new [] (size_t); // Member Operator new []

Void Operator delete [] (void *); // Member operator delete []

String (const char * = ");

//.

}

Void f () {

String * sp = new string ("heap"); // use string :: operator new

INT * ip = new int (12); // Use :: Operator New

Delete IP; // Using :: Operator Delete

Delete sp; // Use string :: delete

}

The survival space where the allocation operation is not related, only which allocation function is called only if the type of the assigned object is called:

String :: string (const char * s)

: s_ (new char [Strlen (s) 1], s))

{}

The character array is assigned memory within the scope of the class string, but the allocation is using the Global Array New, not the Array New "of String, because the CHAR is not String. We can do this via Explicit Qualification.

String :: string (const char * s)

: s_ (STRCPY (Reinterpret_cast

(String :: Operator new [] (Strlen (s) 1)), s))

{}

If we can use the statement of String :: New Char [Strlen (S) 1] to call String Operator New [], but this is illegal, and it will not work. (Although we can use :: New's form to call Global Operator New and Global Operator New [], use :: Delete's form to call Global Operator Delete and Global Operator Delte [].

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

New Post(0)