[Forward] difference malloc in C ++ and the new

Original Address: https://blog.csdn.net/linux_ever/article/details/50533149

10-point difference between the new and malloc

1. Application of a memory location

new operator dynamically allocated memory space for the object from the free store (free store), the malloc function to dynamically allocate memory from the heap. C ++ free store is based on an abstraction of the new operator, who for memory applications using the new operator, the memory is the free store. The term heap is the operating system, the operating system is maintained by a special memory, dynamically allocated memory for a program, C language malloc allocate memory from the heap, the use of the corresponding free release of allocated memory.

So whether free store is a heap (equivalent to the question whether the new memory can be dynamically allocated on the heap), depending on the implementation details of operator new. Free store may not only pile, may also be a static storage area, which can not see where the operator new to allocate memory for objects.

In particular, new and even can not allocate memory for the object! Locate new functionality can do this:

1 new (place_address) type

place_address as a pointer representative of a memory address. When such an address only the above uses the new operator, the new operator to call a specific operator new, this version is the following:

1  void * operator  new new (size_t, void *) // not allowed to redefine this version of operator new

The operator new does not allocate any memory, it simply returns a pointer argument, then the right expression is responsible for initiating new work object in place_address specified address.

2. Return the type of security

When the new operator memory allocation successful, returns a pointer to the object type, the object type in strict matching, without the need for the type of conversion, it is in line with new type of operator safety. The malloc memory allocation is successful return void *, * need to be converted into a pointer type we need through the mandatory conversion will be void.
Type of security can be largely equivalent to the memory security, type-safe code does not attempt memory area method I had not been authorized. C ++ on the type of security can have a lot to say.

3. When the return value of the memory allocation failure

When the new memory allocation fails, it will throw an exception bac_alloc, it does not return NULL; returns NULL when malloc memory allocation failure.
When using the C language, we are used to determine when malloc to allocate memory allocation is successful:

1 int *a  = (int *)malloc ( sizeof (int ));
2 if(NULL == a)
3 {
4     ...
5 }
6 else 
7 {
8     ...
9 }

Novice C ++ into the camp from the C language could put this habit into C ++:

1 int * a = new int();
2 if(NULL == a)
3 {
4     ...
5 }
6 else
7 {   
8     ...
9 }

In fact, doing so does not make sense, because the new will never return NULL, and the program can be executed if the statement has been explained to the memory allocation successful, if the failure would have thrown an exception. The correct way is to use the exception mechanism:

1 try
2 {
3     int *a = new int();
4 }
5 catch (bad_alloc)
6 {
7     ...
8 }

If you want to understand the way exceptional basis, you can see http://www.cnblogs.com/QG-whz/p/5136883.html C ++ exception mechanism analysis.

4. Do you need to specify the size of memory

When necessary to specify the new operator for memory allocated memory block size, the compiler assumes calculated according to the type of information, it is necessary to explicitly malloc that the memory size required.

. 1  class A {...}
 2 A = * PTR new new A;
 . 3 A * PTR = (A *) the malloc ( the sizeof (A)); // need to explicitly specify the required memory size sizeof (A);

Of course, I am here for us to use malloc to allocate memory for custom type is not very suitable, please see the next one.

5. whether to call the constructor / destructor

Using the new operator will allocate memory when the object is subjected to three steps:

  • Step: call operator new function (for operator new array is []) allocate a large enough, the original, unnamed memory space for storing objects of a specific type.
  • Step two: Run the appropriate compiler constructor to construct the object, and its incoming initial value.
  • Third: the object construction is completed, returns a pointer to the object.

Undergoes two steps when using the delete operator to release the object memory:

  • The first step: the calling object destructor.
  • Step two: the compiler calls operator delete (or operator delete []) function to release memory space.

In summary, the constructor new / delete objects will call / destructor to complete the constructor / destructor object. The malloc does not. If you are never too long-winded can look at my example:

 1 class A
 2 {
 3 public:
 4     A() :a(1), b(1.11){}
 5 private:
 6     int a;
 7     double b;
 8 };
 9 int main()
10 {
11     A * ptr = (A*)malloc(sizeof(A));
12     return 0;
13 }

Set a breakpoint in return, the memory pointed to by ptr viewing content:

A default constructor can be seen has not been invoked, because the data members of the values ​​of a, b has not been initialized, which is why I said above, use malloc / free to handle C ++ custom type is inappropriate, in fact, more than custom type, usually required in the standard library constructed / destructed all types unsuitable.

And when used to allocate new objects:

1 int main()
2 {
3     A * ptr = new A;
4 }

Check the assembly code generated by the program can be found, the default constructor is called A:

6. The process of arrays

C ++ provides new [] and delete [] to deal specifically with array type:

PTR = * A new new A [ 10 ]; // allocate objects 10 A

Using new [] allocated memory must use the delete [] to be released:

delete [] ptr;

n- EW reflected support for the array in its respective calls the constructor initializes each element of an array, for each object call the destructor release objects. Note that delete [] to the new [] supporting the use of, or will find an array of objects partial release of the phenomenon, caused by a memory leak.

As for malloc, you know it and to put on a piece of memory array or something else, anyway, it will give you an original memory, giving you a memory address on the bin. So if you want an array of dynamic memory allocation, we also need to manually customize the size of the array:

int * PTR = ( int *) the malloc ( the sizeof ( int )); // allocate an array of 10 elements int

 

Whether 7.new with malloc can call each other

operator new /operator delete的实现可以基于malloc,而malloc的实现不可以去调用new。下面是编写operator new /operator delete 的一种简单方式,其他版本也与之类似:

 1 void * operator new (sieze_t size)
 2 {
 3     if(void * mem = malloc(size)
 4         return mem;
 5     else
 6         throw bad_alloc();
 7 }
 8 void operator delete(void *mem) noexcept
 9 {
10     free(mem);
11 }

8.是否可以被重载

opeartor new /operator delete可以被重载。标准库是定义了operator new函数和operator delete函数的8个重载版本:

 1 //这些版本可能抛出异常
 2 void * operator new(size_t);
 3 void * operator new[](size_t);
 4 void * operator delete (void * )noexcept;
 5 void * operator delete[](void *0)noexcept;
 6 //这些版本承诺不抛出异常
 7 void * operator new(size_t ,nothrow_t&) noexcept;
 8 void * operator new[](size_t, nothrow_t& );
 9 void * operator delete (void *,nothrow_t& )noexcept;
10 void * operator delete[](void *0,nothrow_t& )noexcept;

我们可以自定义上面函数版本中的任意一个,前提是自定义版本必须位于全局作用域或者类作用域中。太细节的东西不在这里讲述,总之,我们知道我们有足够的自由去重载operator new /operator delete ,以决定我们的new与delete如何为对象分配内存,如何回收对象。

而malloc/free并不允许重载。

9. 能够直观地重新分配内存

使用malloc分配的内存后,如果在使用过程中发现内存不足,可以使用realloc函数进行内存重新分配实现内存的扩充。realloc先判断当前的指针所指内存是否有足够的连续空间,如果有,原地扩大可分配的内存地址,并且返回原来的地址指针;如果空间不够,先按照新指定的大小分配空间,将原有数据从头到尾拷贝到新分配的内存区域,而后释放原来的内存区域。

new没有这样直观的配套设施来扩充内存。

10. 客户处理内存分配不足

在operator new抛出异常以反映一个未获得满足的需求之前,它会先调用一个用户指定的错误处理函数,这就是new-handler。new_handler是一个指针类型:

1 namespace std
2 {
3     typedef void (*new_handler)();
4 }

指向了一个没有参数没有返回值的函数,即为错误处理函数。为了指定错误处理函数,客户需要调用set_new_handler,这是一个声明于的一个标准库函数:

1 namespace std
2 {
3     new_handler set_new_handler(new_handler p ) throw();
4 }

set_new_handler的参数为new_handler指针,指向了operator new 无法分配足够内存时该调用的函数。其返回值也是个指针,指向set_new_handler被调用前正在执行(但马上就要发生替换)的那个new_handler函数。

对于malloc,客户并不能够去编程决定内存不足以分配时要干什么事,只能看着malloc返回NULL。

总结

将上面所述的10点差别整理成表格:

特征 new/delete malloc/free
分配内存的位置 自由存储区
内存分配失败返回值 完整类型指针 void*
内存分配失败返回值 默认抛出异常 返回NULL
分配内存的大小 由编译器根据类型计算得出 必须显式指定字节数
处理数组 There are dealing with an array of new version of the new [] Memory allocation after a user needs to calculate the size of the array
Assigned expanded memory Not intuitive handling Simple to use realloc complete
Whether or not to call each other You can see the specific operator new / delete achieve Can not call new
Out of memory when allocating memory Customers can specify the handler or distributor re-enactment Can not be handled by user code
Function overloading allow Not allowed
The constructor and destructor transfer Do not call

malloc you would like a piece of raw land, you need to own up to what kind of land sown

The new plan to help you land a good block (array), to help you sowing the seed (constructor), also provides other facilities for your use:

Of course, malloc is not to say not as new, they each have, where applicable. In C ++, this emphasis on OOP language, using new / delete is naturally more appropriate.

Thank you for your patience to read.

Guess you like

Origin www.cnblogs.com/ygsworld/p/11261810.html