C + + can be used in two ways when creating an object: (for example, a class named Test) test test or test* pTest = new Test ().
Both methods can instantiate an object, but there is a big difference between the two methods, the difference is that the object content is in the same memory space, it is known that there are three ways to allocate memory
(1) Allocation from a static storage area. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block. For example, global variables, static variables.
(2) Create on the stack. When executing a function, the storage unit of the local variable within the function can be created on the stack, and the memory space of those local variables is reclaimed after the function execution ends. Allocating memory space on the stack is highly efficient, but allocates a limited amount of memory.
(3) allocated from the heap. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete.
So when you use test test to allocate memory space to an object, is it allocated in the heap or in the stack? Practice is the only standard for testing truth, with the procedure as proof:
- #include <iostream>
- using namespace Std;
- Class Testnew
- {
- Private
- int ID;
- Public
- testnew (int ID);
- ~testnew ();
- };
- testnew::testnew (int ID)
- {
- this->id = ID;
- }
- Testnew::~testnew ()
- {
- Std::cout<< objects<<this->id < <"perform destructors"<< Std::endl;
- }
- void Test ()
- {
- Testnew test (1);//Create object 1 without using the new
- Testnew *pTest = new Testnew (1);//Create Object 2, use new
- }
- int main ()
- {
- Test ();//This place is a bit of a problem, ptest no processing, will lead to memory leaks, practical application should pay attention to
- }
From the running result, we can conclude that when creating an object without using new , the object's memory space is in the stack, and its scope is only inside the function, and the destructor is called after the function executes and the object is deleted.
using new to create the object is created in the heap, and the programmer must manually manage the object's memory space.
Usually seldom write things, the tutor advised to read some of the technical blog at ordinary times, I also want to write some learning experience, the first attempt (low level), some things expressed unclear or have problems ... I hope you will be very grateful for your criticism and advice.
c++--the difference between new and no new when creating a class (RPM)