Memory Management and memory management in C ++

Source: Internet
Author: User

Memory Management and memory management in C ++

In C ++, memory management is also indispensable. In C ++, if there is a new place, delete should be considered when writing code. Heap memory allocated by new is not automatically released at the end of the function. If I do not delete the heap memory I allocated, it will cause memory leakage. Therefore, we must learn to manage memory and avoid Memory leakage. The memory management mechanism in C ++ is not quite the same as that in OC. The ARC mechanism in OC saves programmers a lot of trouble in memory management, but there is no ARC in C ++, so we need to manage the memory we opened up by ourselves. Java also has its own memory management mechanism, such as the close of various resources obtained in JDBC in finally.

So under what circumstances will Memory leakage occur in the program we write? Next we will give a simple example to analyze the memory management mechanism in C ++.

1. create a test class TestClass. The TestClass class has a private property (pointer type), a constructor, A destructor, and a display method for outputting object information.

The Declaration of the test class is as follows:

12345678910111213 // Memory management test classclass TestClass{private:    char *name;public:    // No parameter Constructor    TestClass();    // Destructor    ~TestClass();    // Description    void display();};

Define the class implementation method in the xxx. cpp File

Implement constructor: Allocate space to the property pointer when implementing constructor. Otherwise, the property pointer does not allocate memory addresses. The program crashes during the call and heap allocation is performed using the new method.

123456789 // No parameter ConstructorTestClass::TestClass(){    cout << "TestClass()" <<endl;    // Allocate memory to pointer attributes (heap allocation)    this->name = new char[255];    // Initialize    strcpy(this->name, "ludashi");}

To implement the destructor, delete the heap allocated memory in the constructor. Otherwise, the memory leakage will occur.

123456 // DestructorTestClass::~TestClass(){    delete [] this->name;    cout << "~TestClass()" << endl;}

Implement the display function to print the name.

12345 // Descriptionvoid TestClass::display(){    cout << this->name <<endl;}

2. Test the main function.

Heap allocation during Object Instantiation: manual memory release is required. Otherwise, memory leakage may occur.

12 // Initialize the TestClass class and allocate the heap. delete is required.TestClass * testClass = new TestClass();

Stack allocation of instantiated objects: No need to manually release the memory, and the stack memory will be automatically released when braces are over.

12 // Stack allocation, no delete, automatically released after braces TestClass stackClass = TestClass()

Information printing and Output

1 testClass->display();

Call delete to release heap allocation objects

1 delete testClass;

3. program running result: If delete testClass is not added, only one destructor will be called, because the heap allocated objects will not be automatically released and need to be manually released. Otherwise, memory leakage will occur.

12345 TestClass()TestClass()ludashi~TestClass()~TestClass()

4. copy constructors

If you add the following sentence to the main function, the program will collapse during running. If you want the program to run normally, you can delete [] this-> name in the Destructor; you can run it after you comment it out. However, this will cause memory leakage. So let's take a look at why the program will collapse when we add the following sentence? The reason is that copyTest and stackClass point to the same stack memory. When one of them calls the destructor, it will delete the name, another error occurs when the Destructor calls delete. How can we basically solve the problem? Next, it's time to copy the constructor.

1 TestClass copyTest = stackClass;

The following is the definition method of the copy constructor.

12345678 // Copy the constructorTestClass::TestClass(const TestClass &test){    // Allocate new memory in the heap    this->name = new char[255];    // Copy    strcpy(this->name, test.name);}

The copy constructor is called in the main function, so there will be no problems with this code.

1 TestClass copyTest = stackClass;

5. When I mention memory management, I can't help but think of the phrase "first constructed and then analyzed structure" when I was a beginner in C ++. When there is new, I have to think about delete to avoid Memory leakage.

The above copy constructor is used to assign values to new objects when declaring objects. In this case, excessive release may occur;

123 TestClass  test1 = TestClass();TestClass  test2 = TestClass();test2 = test1;

Next we will reload the = operator (operator = ).

123456 // Value assignment between objects: Operator overloadTestClass & TestClass :: operator = (const TestClass &test){    strcpy(this->name, test.name);    return *this;}

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.