write two classes in C + + one can only allocate space in the stack one can only be allocated in the heap.
Answer: (1) The code is as follows
#include <iostream>using namespacestd; //memory can only be allocated on the heapclassheaponly { Public: Heaponly () {cout<<"Construct."<<Endl; } voiddestory () {Delete This; } Private: ~heaponly () {}}; //space can only be allocated on the stackclassstackonly { Public: Stackonly () {}~stackonly () {}Private: void*operator New(size_t size)//The new operator is privatized and cannot be called outside { } }; intMain () {heaponly*ho=Newheaponly (); HO-destory (); //heaponly He;//Compile Error: Heaponly::~heaponly ": Unable to access private member (declared in" Heaponly "Class), so the object's space cannot be allocated through the stackstackonly so; //stackonly *st=new stackonly (); //stackonly::operator New ": Unable to access private member (declared in" Stackonly "Class)}(2) Introduction to stack allocation memory
The memory used by the one compiled C + + program is divided into the following sections:
1, stack: Automatically allocated and released by the compiler, the value of the stored function parameters, the value of local variables, and even the function of the call process is done with the stack. It operates in a manner similar to a stack in a data structure.
2, heap area (heap): Generally by the programmer manually apply and release, if the programmer does not release, the end of the program may be recycled by the OS. Note that it is different from the heap in the data structure, and is distributed in a way similar to a linked list.
3. Global zone (Static): The storage of global variables and static variables is placed in a block, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another adjacent area. The system frees up space after the program ends.
4, the literal constant area: the constant string is put here. The system frees up space after the program ends.
5, program code area: the binary code that holds the function body.
The following example completely shows the memory area of the different variables:
//main.cppintA =0; global initialization ZoneChar*p1; Global uninitialized area main () {intb//in the StackCharS[] ="ABC";//in the StackChar*P2;//in the StackChar*P3 ="123456";//123456/0 in the constant area, p3 on the stackStatic intc =0;//Global (Static) initialization zone//The following allocated 10 and 20 bytes of the area are in the heap areaP1 = (Char*)malloc(Ten); P2=New Char[ -];//(Char*)malloc( -); strcpy (P1,"123456"); //123456/0 in the constant area, the compiler might optimize it to a place with the "123456" that P3 points to. }
the concrete difference between stack and heap (heap).
1, on request
Use the malloc function in C.
The
but note that P1 itself is in the global zone, and P2 itself is in the stack, except that the space they point to is in the heap.
2, post-application response on the system
As long as the remaining space on the stack is greater than the requested space, the system will provide memory for the program, otherwise it will report the exception prompt stack overflow.
First you should know that the operating system has a linked list that records the free memory address. When the system receives a request for a program, it iterates through the list, finds the heap node where the first space is larger than the requested space, and then removes the node from the list of idle nodes and assigns the node's space to the program. also, for most systems, the size of this allocation is recorded at the first address in this memory space, so that the delete or free statements in the code can properly release the memory space. In addition, because the size of the found heap node does not necessarily equal the size of the request, the system automatically re-puts the extra portion into the idle list.
3, the application size limit
Stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack address and the maximum capacity of the stack is the system pre-defined, in windows, the size of the stack is 2M(and some say 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small. For example, under VC6, the default stack space size is 1M (as if it's not clear). Of course, we can modify: Open the project, the Operation menu is as follows: Project->setting->link, select output in category, then set the maximum and commit of the stack in the reserve.
Note : The reserve minimum value of 4byte;commit is reserved in the virtual memory of the page file, it is set to a large size stack will open up a larger value, may increase the memory overhead and startup time.
Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory (the idle part is concatenated with a linked list). It is because the system uses a linked list to store free memory, which is naturally discontinuous, and the traversal direction of the list is from the low address to the high address. in general, 32-bit systems, heap memory can reach 4G of space, from this point of view heap memory is almost no limit. Thus, the space of the heap is more flexible and relatively large.
4, the efficiency of the allocation of space
Stack: The stack is a machine system provided by the data structure, the computer will support the stack at the bottom: the allocation of dedicated register storage stack address, the stack stack out of a special command execution, which determines the efficiency of the stack is high. But programmers can't control it.
Heap: The memory allocated by new or malloc, which is provided by the C/S function library, is generally slower and prone to memory fragmentation. Its mechanism is very complex, for example, in order to allocate a piece of memory, the library function will follow a certain algorithm (the specific algorithm can refer to the data structure/operating system) in the heap memory to search for enough space available, if there is not enough space (possibly due to too much memory fragmentation), It is possible to invoke the system function to increase the memory space of the program data segment, so that there is a chance to divide the memory in sufficient size and then return. This may trigger a switchover of the user state and kernel mentality, the memory application, the cost becomes more expensive. Obviously, the heap is much less efficient than the stack.
5. Storage content in heaps and stacks
Stack: on a function call, the first stack is the address of the next instruction (the next executable statement of a child function call statement) after the main function is called, followed by the individual parameters of the child function. In most C compilers, the arguments are in the right-to-left stack, followed by the local variables in the child functions. Note: Static variables are not in the stack. When the function call ends, the local variable is first out of the stack, then the parameter, and the last stack pointer points to the first saved address, that is, the main function called the completion of the next instruction of the child function, the program continues to run by this point.
Heap: The heap is usually the size of a heap with one byte in the head, and the concrete contents of the heap are arranged by the programmer.
6. Comparison of Access efficiency
This is supposed to be obvious. Take the array on the stack and the array on the heap:
voidMain () {intarr[5]={1,2,3,4,5}; int*arr1; ARR1=New int[5]; for(intj=0; j<=4; j + +) {arr1[j]=j+6; } inta=arr[1]; intb=arr1[1];}
In the above code, the ARR1 (local variable) is in the stack, but the point of the space is actually on the heap, and the access efficiency of the two is, of course, arr high. Because arr[1] can be accessed directly, but access arr1[1], first to access the array's starting address arr1, and then access to arr1[1].
In a word, in short:
The difference between heap and stack can be seen in the following analogy:
Use the stack like we go to a restaurant to eat, just order (declare variable), pay, and eat (use), eat enough to go, do not bother to cut vegetables, wash vegetables and other preparation work and washing dishes, brush pots and other finishing work, his advantage is fast, but the freedom is small.
The use of the heap is like a DIY dish that you like to eat, more trouble, but more in line with their own tastes, and great freedom.
C + + stack issues