Introduction

One of the most common questions that get asked during interviews for C++ programmers is to explain the differences between using malloc and using new. It’s also a fairly common question in some of newsgroups and C++ forums.

(在C++程序猿的面试中,最常见的问题就是使用malloc和new的差别。在小组讨论和C++论坛中,两者之间的差别相同是相当普遍的话题。)

Constructors and Destructors

When you new an object, space for the object is not only allocated but the object’s constructor is called. And similarly when you delete an object, the object’s destructor is called before the memory is released. If you use malloc and free, the destructor and constructor do not get called respectively and obviously, this simply won’t do in C++ except in certain very rare situations where you have classes without any specific destructor/constructors.

(当你new一个对象的时候。不只为对象分配了空间,同事调用了对象的构造函数。相同的。当你delete一个对象时。在内存释放之前会调用对象的析构函数。

假设你使用malloc和free,构造函数和析构函数都不会被调用。对于没有构造函数和析构函数的特殊情况下,这个小样例不会起作用。)

It’s very easy to test this out by using the following test class.

(通过以下的test类。非常容易得到结论)

class Test
{
public:
Test()
{
cout << "Test : ctor\r\n";
}
~Test()
{
cout << "Test : dtor\r\n";
}
void Hello()
{
cout << "Test : Hello World\r\n";
}
};

Create, use and delete the object using new/delete as well as using malloc/free :-

(使用new/delete、malloc/free来创建、使用、删除对象)

int _tmain(int argc, _TCHAR* argv[])
{
cout << "1\r\n";
Test* t1 = new Test();
t1->Hello();
delete t1;
cout << "2\r\n";
Test* t2 = (Test*) malloc(sizeof Test);
t2->Hello();
free(t2);
return 0;
}

You’ll see the following output:-

(你会看到以下输出)

1

Test : ctor

Test : Hello World

Test : dtor

2

Test : Hello World

As obvious from the output, malloc/free did not result in either the destructor or the constructor being called.

(从输出结果能够清楚得到,malloc/free既没有调用构造函数也没有调用析构函数。)

Choosing constructor overloads

For non-array allocations, you can actually specify the specific overload of the constructor that you wish to use as in :- T t = new T(x, y, z); For array allocations using new, the default constructor will get used. If you attempt an array allocation on an object that does not have a default constructor, you get a compiler error .

(对于非数组分配空间。你能够使用T t = new T(x, y, z)去差别重载的构造函数。对于使用new分配的数组空间。默认的构造函数将被调用。

假设对于不存在默认构造函数的对象分配数组空间,将是编译错误。



class Test2

{

public:

Test2(int y)

{

}

};

//…

Test2* t2array = new Test2[10];

For example, if you attempt to compile the above snippet, you’ll get an error

(例,假设你尝试编译以上代码片段。便会得到错误。)

Type-casting forced by malloc

Because malloc returns a void* the caller has to do a type-cast to get it to compile.

(因为malloc的返回值为void*,所以须要进行强制类型转换)

Test* t1 = new Test();

Test* t2 = (Test*) malloc(sizeof Test);

Native types

For native types new/delete and malloc/free work the same way except for the need to type-cast in the case of malloc/free. So it’s just a matter of user preference.

(对于内置的类型,除了malloc/free的强制类型转换外。new/delete和malloc/free的工作方式相同。)

//declaring native type
int* i1 = new int;
delete i1;
int* i2 = (int*) malloc(sizeof(int));
free(i2);
//declaring native type array
char** c1 = new char*[10];
delete[] c1;
char** c2 = (char**) malloc(sizeof(char)*10);
free(c2);

Safety tip

Always delete what you new, and free what you malloc, never mix new with free or malloc with delete.

(总要delete你所new的内容。free你所malloc的内容,千万不要混淆使用。



No realloc alternative for new/delete

The new/delete couple not have a realloc alternative that is available when you use the malloc/free pair. realloc is pretty handy if you want to resize the length of an array or a memory block dynamically, specially since the contents of the array/block remain same up to the shorter of the old and new sizes. To see this in action, see the following code snippet :-

(new/delete的组合没有相似于realloc这种函数。假设你想你想动态又一次设置数组的长度或是内存块的长度,而且须要保留之前的内容,realloc是一个相当方便的操作。为了看看realloc怎样工作的,请看以下的代码块:)

char* p = (char*)malloc(sizeof(char)*12);
strcpy(p,"hello world");
cout << p << "\r\n";
p = (char*)realloc(p, sizeof(char)*24);
strcat(p," from Nish");
cout << p << "\r\n";
free(p);

The output you get will be :-

hello world

hello world from Nish

As you can see from the output, the original contents were retained.

(正如你看到的,原有的内容被保存了。)

To new is C++; To malloc is C; To mix them is sin (混淆C++中的new和C中的malloc是一种犯罪)的更多相关文章

  1. 在dll里malloc/new/cvCreate分配内存,在exe里free/Releases释放内存时会出错。

    写了个程序,在DLL中用malloc分配了一块内存,但是在exe程序中释放,结果程序crash,原因就是:其原因可能是堆被损坏,这也说明 TestMySticker.exe 中或它所加载的任何 DLL ...

  2. new 等于 malloc加构造函数

    1.new 是c++中的操作符,malloc是c 中的一个函数 2.new 不止是分配内存,而且会调用类的构造函数,同理delete会调用类的析构函数,而malloc则只分配内存,不会进行初始化类成员 ...

  3. 转:如何实现一个malloc

    如何实现一个malloc 转载后排版效果很差,看原文!   任何一个用过或学过C的人对malloc都不会陌生.大家都知道malloc可以分配一段连续的内存空间,并且在不再使用时可以通过free释放掉. ...

  4. malloc杀内存于无形

    C语言中的malloc函数是分配内存用的,函数内部生命的变量也会分配内存,但是当函数释放的时候内存也就释放了,这样就不会占用内存了,但是malloc函数不同, 如下 typedef struct No ...

  5. new 与 malloc 的区别

    1, 申请内存所在的位置 new 操作符从自由存储区上为对象动态分配内存空间,而 malloc 函数从堆上动态分配内存.自由存储区是C++基于 new 操作符的一个抽象概念,而堆是操作系统中的术语,是 ...

  6. 对c语言中malloc和free函数的理解

    最近在复习c语言的时候再次用到了malloc函数和free函数,此处着讲解一下自己对这两个函数的理解和认识. 一. malloc函数和free函数的基本概念和基本的用法 对于malloc函数: 1.  ...

  7. 【转载】new和malloc的区别

    本篇随笔为转载,原贴地址:C++中new和malloc的十点区别. 前言 几个星期前去面试C++研发的实习岗位,面试官问了个问题: new与malloc有什么区别? 这是个老生常谈的问题.当时我回答n ...

  8. malloc 函数工作机制(转)

    malloc()工作机制 malloc函数的实质体现在,它有一个将可用的内存块连接为一个长长的列表的所谓空闲链表.调用malloc函数时,它沿连接表寻找一个大到足以满足用户请求所需要的内存块.然后,将 ...

  9. C语言学习017:malloc和free

    malloc和free都包含在<stdlib.h>头文件中 局部变量由于存储在栈中,一旦离开函数,变量就会被释放,当我们需要将数据持久使用,就需要将数据保存到堆中,而在堆中申请内存空间就需 ...

随机推荐

  1. 百度蜘蛛IP地址到底代表什么含义?

    百度蜘蛛IP地址到底代表什么含义,是不是不同的ip地址所代表的含义不一样呢?对权重和抓取是否有影响?哪些是无效的蜘蛛,哪些是站长工具的蜘蛛,那些又是百度自己真正的蜘蛛?百度蜘蛛,是百度搜索引擎的一个自 ...

  2. vb常用的内部函数(二):字符串函数

    len(string):计算字符串长度函数.返回字符串string中字符的个数.一个汉字为一个字符,空格也为一个字符,空字符串的长度为0. Ltrim(string).Rtrim(string).Tr ...

  3. The Node.js Event Loop, Timers, and process.nextTick() Node.js事件循环,定时器和process.nextTick()

    个人翻译 原文:https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ The Node.js Event Loop, Ti ...

  4. 抓取豆瓣的电影排行榜TOP100

    #!/usr/bin/env python # -*- coding:utf-8 -*- """ 一个简单的Python爬虫, 用于抓取豆瓣电影Top前100的电影的名称 ...

  5. 11g Oracle Rac安装(基于linux6)可能出现的问题

    11g Oracle Rac安装(基于linux6)可能出现的问题汇总: 7)使用"yum"命令执行节点的自动配置失败. 修改一下 /etc/resolv.conf,添加: nam ...

  6. readb(), readw(), readl(),writeb(), writew(), writel() 宏函数

    参见: http://blog.csdn.net/hustyangju/article/details/20448339

  7. PatentTips - Controlling voltage and frequency

    BACKGROUND OF THE INVENTION Mobile devices, such as but not limited to personal data appliances, cel ...

  8. [Python]Use Flask-Admin with PostgreSQL

    This code recipe gives you an idea of how to use Flask-Admin with postgresql database. from flask im ...

  9. jsp出现错误can not find the tag directory /web-inf/tags

    百度google了一大圈没找到中文答案,无奈之下硬着头皮看了一个英文答案http://stackoverflow.com/questions/11502703/eclipse-can-not-find ...

  10. ip反查域名的详细信息(多种方法)

    不多说,直接上干货! 至于这里怎FQ,很简单,请见我下面的博客! kali 2.0安装 lantern(成功FQ) shadowsocks(简称SSFQ软件)步骤详解 FQ软件lantern-inst ...