How does compiler control help in allocating and freeing memory in C ++?

In a book in C ++, I read that malloc()both free()are personal functions and, therefore, are beyond the control of the compiler.

However, if you have an operator to perform the combined action of allocating and initializing dynamic storage ( new) and another operator to perform the combined action of cleaning and freeing memory ( delete), the compiler can still guarantee that the constructors and destructors will be called for all objects.

So, I want to know how this is done by the compiler? Any example or demo will be listed.

Thanks in advance.

+4
source share
3 answers
Function

mallocreturns a piece of continuous memory that's all. How you type and use text (for your objects) is your problem.

While the operator newreturns the objects allocated in memory. Although both return a pointer, in the end you get constructed objects, not raw memory in C ++. Here, the focus shifts from low-level memory processing to processing objects with which type safety arises. Reason newdoes not return void*.

, , C, , , . ++ new , , , , . , , , , , .

:

int *ptr = malloc(sizeof(char) * 4);

, 4, , . char int , C. , , malloc , , ptr. , , ( ?) . , .

++

int *ptr = new char[4];

; int *ptr = new int;, . ++ , , , , . , , ++. casting : . ( , ).

+4

"" ; . ++ , (). , , , .

+2

new delete - ++.

++ / .

,

struct Test() { }
Test *a = new Test();

- ( )

Test *a = (Test *)malloc(sizeof(Test));
if (a == nullptr) { throw std::bad_alloc; }
try
{
    a.Test(); //call constructor
}
catch (...)
{
     //constructor exception, free the memory first, then re-throw
     free(a);
     throw;
}

, ,

struct Test() { }
Test *a = new Test[10];

- ,

Test *a = (Test *)malloc(sizeof(Test) * 10);
if (a == nullptr) { throw std::bad_alloc; }
int i;
try
{
    for (i = 0; i < 10, i++)
        a[i].Test(); //call constructor
}
catch (...)
{
     //call destructor for all constructed objects
     for (int j = 0; j < i; j++)
         a[j].~Test();

     free(a);
     throw;
}

.

0

All Articles