In C ++, when to use a A; and when to use a = new;

Source: Internet
Author: User

Note: The content here is excerpted on the Internet. Here, we will summarize the content for future search.

New allocates memory on the heap. It needs to be released using delete. Otherwise, memory leakage will occur (the memory used is not immediately released, resulting in A waste of memory). After a is executed in the right braces, memory will be automatically released, such as int main () {A; // defines an object a * p = new a; // defines an object on the stack, its pointer is saved in p. Note that the object defined on the heap has no name. You must use the pointer to save return 0;} // when a is here, the memory it occupies will be recycled and p, unless delete p is called; otherwise, the memory will never be recycled. After the pointer p is discarded, the memory is not released,
Cannot be used again, resulting in a waste of memory
Next we will introduce you in detail how to use the Dynamic Allocation of memory (new) refer to the word. I hope that you can now understand when new can be used and how to use new,
The following content is comprehensive and easy to understand. It is completely from my own learning summary and is not a copy. The new memory for dynamic allocation can be seen in the word 1. The life cycle of global and local objects is strictly defined, and programmers cannot change their life cycle in any way. However, sometimes it is necessary to create some projects that can be controlled by programmers in their lifetime.
Objects. Their Distribution and release can be determined based on the operation in the program running. Now we need to use the new operator. 2. the dynamically allocated memory is allocated from the heap. The dynamically allocated storage area is determined at runtime. The dynamically allocated storage area can be automatically expanded as needed. 3. local variables are generally stored in the stack. the stack is an advanced storage structure, but the stack is not. 4. use new to dynamically allocate memory in C ++, and delete to release the memory previously allocated by new. 5. using the new operator, the system allocates memory for the object from the free storage area and returns a pointer to the object, that is, the address of the object. The new operator features:
The object allocated with the new operator has no name. Operations on this object must be performed indirectly through pointers. For example, the new int type object is allocated from the free storage area,
However, this object cannot be operated, but such a space is allocated from the storage area. Statement int * p = new int indicates that an int object is allocated from the free storage area and
Address Assigned to p. Now p is the address of the int object allocated with new, and * p is the value there. The statement int I; int * p = & I; and int * p = new int both grant the address of the int variable
The pointer, but the difference is that the first sentence can use the name I and * p to access the int type variable, and the last sentence can only use * p to access the variable, that is to say, p points to the memory with no name. 6. dynamically create an array: int * p = new int [11]; when creating a dynamic array, there must be [] square brackets and the dimension must be included, however, the first dimension of the array can be a complex one.
Expression. The method for accessing the content in the address is * p to access the first element in the array, p [1] to ask the second element, and so on. Example of creating two groups of Arrays:
Int (* p) [102] = new int [4] [102]. 7. initialization of the dynamically created object: int * p = new int (102) This statement indicates that the newly created object directed by p is initialized to 102. The Dynamic Object creation method is in the type name
Followed by a pair of parentheses. 8. Default initialization of dynamically created objects: Initialize with an empty parentheses after the type name,
      int *p=new int (); int *ps=new string(); cls *pc=new cls();
The first statement initializes the object value to 0, and the second statement provides the default constructor for the string class, whether the program needs to explicitly do not initialize, or require value Initialization
Will call the default constructor to initialize this object. For built-in or non-default constructor types, different initialization methods may differ significantly.
For example, int * p = new int; int * p = new int (); the first statement is not initialized, and the second statement is initialized to 0. 9. arrays dynamically created with new cannot be initialized, and initialization value sets cannot be created. 10. Run out of memory: if the program has used up all available memory, the new expression may fail. If the new expression cannot obtain the required memory space,
The system will throw an exception named bad_alloc. 11. You can use the new operator to allocate memory in one function, but use delete in another function to release memory space. delete can only be used to release the space previously allocated by using new,
Do not use delete to release memory not allocated by new. Do not use delete to release the same memory twice. Use delete [] to release dynamic arrays. For example:
Int * p = new int [10]; delete [] p; [] square brackets are required to delete an array. Delete does not have to be used as a new pointer,
For example, int * p = new int; int * x = p; delete x; will be valid. if the pointer value is 0, it is valid to perform the delete operation on it, but it does not make any sense. 12. suspension pointer: After executing delete p, the content of the address pointed to by p is released, and the pointer p is not deleted, you can also point p to another new memory block,
Therefore, p points to the address of the object to which it originally points. However, the content pointed to by p has been released, so p is no longer valid and is not defined. Such a pointer is called a suspension pointer.
Hanging pointers often cause program errors and are difficult to detect. 13. Static concatenation: if an array is created through declaration, memory space is allocated to the array when the program is compiled. no matter whether the program uses an array or not, the array is there, occupying the memory.
The memory allocated to the array during compilation is called static concatenation. This means that the array is added to the program during compilation. But when new is used, if an array is required in the running stage, it is created,
If you do not need it, do not create it. You can also select the length of the array when running the program. This is called dynamic concatenation. This means that the array is created when the program runs. This array is called
Dynamic Array. When static concatenation is used, you must specify the length of the array during programming. When dynamic concatenation is used, the program determines the length of the array at runtime. 14. Dynamic Allocation and collection of const constant objects: Like other constants, a dynamically created const object must be initialized at creation and its value cannot be modified once initialized.
For example: const int * p = new const int (111); delete method: delete p; although the programmer cannot modify the value of the const object, the object itself can be undone. 15. Note: you cannot create a const array with built-in type Elements (except the class array string) in the free storage area. Because We Cannot initialize the elements of the built-in type array created with new.
For example, const int * p = new const int [11]; will be incorrect. 16. Note: If a resource is allocated with "new", and the resource is not released with "delete", the resources allocated with "new" will be occupied by the worker. 17. common error: if the memory is dynamically allocated to a pointer and the address of another variable is paid to the pointer, the pointer points to a static address,
Instead of the original Dynamic Address. If delete is used to delete the pointer, an error occurs because the pointer points to a static address and cannot be deleted using delete.
Static address pointer. For example, if int * p = new int (1), the pointer p points to a dynamic memory and can delete it, but if you execute the statement int a = 2; p = &;
In this case, the content pointed to by the pointer is changed, and the original dynamic memory address is changed to the current static memory address. If the delete operation is performed on the pointer p, an error occurs,
Because you are still deleting a static pointer, and delete can only delete dynamic pointers. For example, the dynamic allocation object newclass hyong {public: int a, B, c; hyong () {a = B = c = 0;} hyong (int I) {a = B = c = I ;}~ Hyong () {cout <"xigou" <"/n" ;}}; int main () {hyong * p = new hyong; hyong * p1 = new hyong (); cout <p-> a <p1-> a <"/n"; // outputs two zeros, all call the default constructor initialization pointer. Int * p2 = new int; int * p3 = new int (); int * p4 = new int (1); // The Initialization Method of memory allocation for new.
For the class type, p2 is not initialized to obtain a random value, p3 is initialized to 0, and p4 is initialized to 1. Cout <* p2 <"/n" <* p3 <"/n" <* p4 <"/n"; // outputs a random value, one 0, one 1 int I = 10; delete p4; cout <* p4 <"/n"; // p4 is now a suspension pointer, delete only releases the content of the address pointed to by pointer p4,
But the pointer p4 still points to the original address, but there is no content, and the pointer p4 can still point to another address. P4 = & I; cout <* p4 <"/n"; // you can re-assign an address to the suspension pointer p4. Const int * p5 = new int; const int * p6 = new int (4); cout <* p5 <* p6 <"/n "; // output a random value and 4. The const constant must be initialized during declaration. Int * p7 = new int [2]; p7 [0] = 5; p7 [1] = 6; cout <p7 [0] <p7 [1] <"/n"; // defines a dynamic array,Dynamic Arrays cannot be initialized during declaration.// Const int * P8 = new int [2]; // error, because dynamic arrays cannot be initialized during declaration, and const must be initialized during declaration, causing a conflict, error. Delete P1; Delete P; // Delete P, P1; // Note: if this statement is used, only one destructor is called. Delete P2, P3, P4, P5, P6; Delete [] P7; // int * P8 = new int (9); int A = 8; P8 = &; delete P8; // error. The current pointer P8 points to a static address again,
Deleting a static address using Delete will cause an error. }
A is a class. When a is used in the same class, new A is used in different classes.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.