1, in C + +, generally use New/delete to apply and release memory, for the following several new usages, what is the difference?
int *p1 = new Int;int *p2 = new int (), int *p3 = nre int (1);//define Class A; A *p4 = new A; A *P5 = new A (); A *p6 = new A[10]; A *P7 = new a[10] ();
according to the description of new in the fourth edition of <c++ Primer, new A belongs to the default Initializing of dynamically allocated Objects (which dynamically creates object defaults). New A () belongs to value initalizing of dynamically allocated (the value initialization of dynamically created objects).
|
New A |
New A () |
New A (parameters) |
A is a built-in type |
No initialization action |
Initialize the value, example a is an int type, then initialize to 0 |
To initialize the value, a is initialized to parameters |
A is class/struct |
Call the default constructor, whether the member in a initializes a constructor-dependent implementation |
If the default constructor is customized, the custom default constructor is called, otherwise the system default constructor is called and a value is initialized for the member in a. |
Call A's custom constructor |
So the above code performs the following results, respectively:
- P1 points to an uninitialized int space
- P2 points to an initialized space with a value of 0
- The P3 points to a initialized int space with a value of 1
- P4 points to an instance a that invokes the default constructor, unless the default constructor of a initializes the A, otherwise the members of a are all uninitialized variables
- P5 points to an instance a with a default constructor, if a customizes the default constructor, the initialization of a member variable depends on the custom default constructor, whereas the member variable of a is all initialized
- P6 P7 points to an array of instance a that invokes the default constructor, with the same execution structure as P4 P5.
2, C + + in a new array, release the time to note the wording.
Class A {public: int A;}; int main () { a *p = new a[10];//P points to an address that has 10 instances of a delete p;//releases a delete [] P Release 10 times return 0;}
New [] Returns an address that moves back 4 bytes and uses that 4 to hold the size of the array! And new doesn't have to move these four bytes back.
Delete[] calls the destructor of the specified number of times according to the value of that 4 byte, and the same delete does not need that four bytes
Go back to the high quality C + + Programming Guide:
delete []objects; The right usage
Delete objects; Incorrect use of
The latter equivalent to delete objects[0], missing another 99 objects strictly should say:
The latter is equivalent to a destructor that calls only objects[0], misses a destructor that calls another 99 objects, and causes an exception if the destructor is present after the call is released, if the object has no destructor, and the statement is the same as delete []objects
New in C + +