zoukankan      html  css  js  c++  java
  • malloc() vs new

      Following are the differences between malloc() and operator new.

      (1)new calls constructors, while malloc() does not.

      In fact primitive data types (char, int, float.. etc) can also be initialized with new.

      For example, below program prints 10.

     1 #include<iostream>
     2  
     3 using namespace std;
     4  
     5 int main()
     6 {
     7    int *n = new int(10); // initialization with new()
     8    cout<<*n;
     9    getchar();
    10    return 0;
    11 }

      (2)new is an operator, while malloc() is a fucntion.

      (3)new returns exact data type, while malloc() returns void *.

      (4)Operator new throws an exception if there is not enough memory, malloc returns a NULL.

      (5)Operator new[] requires to specify the number of objects to allocate, malloc requires to specify the total number of bytes to allocate.

      (6) malloc() returns void *, which has to be explicitly cast to the desired type but new returns the proper type.

      (7) Operator new/new[] must be matched with operator delete/delete[] to deallocate memory, malloc() must be matched with free() to deallocate memory.

      (8) The new/delete couple does not have a realloc alternative that is available when malloc/free pair is used. realloc is used to resize the length of an array or a memory block dynamically.

      Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

      转载请注明:http://www.cnblogs.com/iloveyouforever/

      2013-11-26  09:56:08

  • 相关阅读:
    PHP上传文件到阿里云OSS,nginx代理访问
    知识点
    WEB安全----XSS和CSRF
    note3
    linux crontab 执行任务(7秒执行)
    composer的自动加载机制(autoload)
    php-fpm的执行方式 (进程管理模式)
    CSS3:pointer-events | a标签禁用
    CSS3: @font-face 介绍与使用
    css公共样式 | 标签元素初始化
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3442722.html
Copyright © 2011-2022 走看看