Reload the C ++ new operator
You know C ++
New
Operator and operator new
? Maybe you will ask, are they different?
When you write the following code,
String * pA = new string ("memory managerment ");
You are using new
Operator, this operator and sizeof
C ++
Supported at the language level. You cannot change its semantics. What it does remains unchanged: allocate enough memory to hold the object, and then call the constructor to initialize the memory allocated in the previous step. New
The operator always does these two things, and you cannot change its behavior.
What you can change is the first step of behavior, how to allocate raw to objects
Memory. Operator
New
The function is used to allocate original memory to objects. New
The first step of the operator is to call operator new.
. You can reload this function. Its prototype is as follows:
Void * operator new (size_t size );
The Return Value of the function is void *,
This function returns a pointer. This Pointer Points to the native memory for initialization. Its semantics is like malloc.
. Actually, it calls malloc internally.
. Parameter size
Memory size to be allocated. You can add additional parameters when reloading, but the first parameter type must be size_t.
In most cases, you do not need to call operator new,
In case you need to call it, the calling format is as follows:
Void * rawmemory = Operator new (sizeof (string ));
Function operator new
Returns a pointer pointing to a piece that can hold a string.
Object Memory.
Like malloc
Same, operator new
The only responsibility of the constructor is to allocate memory. Set operator new
The uninitialized pointer is returned to construct an object that is new.
Operator. When your compiler encounters the following code:
String * pA = new string ("memory managerment ");
Its pseudo-code class is as follows:
Void * Memory = Operator new (sizeof (string ));
Call string: string ("memory managerment") on
Memory
;
String * pA = static_cast <string *> (memory );
The second section contains the call of the constructor. This is called by your compiler. So you may ask, can programmers manually call constructor? The answer is no. But the compiler also provides you with another compromise that you can achieve.
It must be noted that calling constructor on an existing object makes no sense. Because constructors are used to initialize objects. But sometimes some memory has been allocated but not initialized, You need to construct an object in the memory. You can use operator new
A special version of the function. A term is placement new.
To do this.
Return to the previous string example. We can use placement new in this way.
:
Void * Memory = Operator new (sizeof (string ));
String * pA = new (memory) string ("memory
Managerment ");
The above two sentences are equivalent to new
Operator.
This is Operator new.
And placement new
All secrets. Generally, you do not need to overload or explicitly call these two functions.