To new is C++; To malloc is C; To mix them is sin (混淆C++中的new和C中的malloc是一种犯罪)
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是一种犯罪)的更多相关文章
- 在dll里malloc/new/cvCreate分配内存,在exe里free/Releases释放内存时会出错。
写了个程序,在DLL中用malloc分配了一块内存,但是在exe程序中释放,结果程序crash,原因就是:其原因可能是堆被损坏,这也说明 TestMySticker.exe 中或它所加载的任何 DLL ...
- new 等于 malloc加构造函数
1.new 是c++中的操作符,malloc是c 中的一个函数 2.new 不止是分配内存,而且会调用类的构造函数,同理delete会调用类的析构函数,而malloc则只分配内存,不会进行初始化类成员 ...
- 转:如何实现一个malloc
如何实现一个malloc 转载后排版效果很差,看原文! 任何一个用过或学过C的人对malloc都不会陌生.大家都知道malloc可以分配一段连续的内存空间,并且在不再使用时可以通过free释放掉. ...
- malloc杀内存于无形
C语言中的malloc函数是分配内存用的,函数内部生命的变量也会分配内存,但是当函数释放的时候内存也就释放了,这样就不会占用内存了,但是malloc函数不同, 如下 typedef struct No ...
- new 与 malloc 的区别
1, 申请内存所在的位置 new 操作符从自由存储区上为对象动态分配内存空间,而 malloc 函数从堆上动态分配内存.自由存储区是C++基于 new 操作符的一个抽象概念,而堆是操作系统中的术语,是 ...
- 对c语言中malloc和free函数的理解
最近在复习c语言的时候再次用到了malloc函数和free函数,此处着讲解一下自己对这两个函数的理解和认识. 一. malloc函数和free函数的基本概念和基本的用法 对于malloc函数: 1. ...
- 【转载】new和malloc的区别
本篇随笔为转载,原贴地址:C++中new和malloc的十点区别. 前言 几个星期前去面试C++研发的实习岗位,面试官问了个问题: new与malloc有什么区别? 这是个老生常谈的问题.当时我回答n ...
- malloc 函数工作机制(转)
malloc()工作机制 malloc函数的实质体现在,它有一个将可用的内存块连接为一个长长的列表的所谓空闲链表.调用malloc函数时,它沿连接表寻找一个大到足以满足用户请求所需要的内存块.然后,将 ...
- C语言学习017:malloc和free
malloc和free都包含在<stdlib.h>头文件中 局部变量由于存储在栈中,一旦离开函数,变量就会被释放,当我们需要将数据持久使用,就需要将数据保存到堆中,而在堆中申请内存空间就需 ...
随机推荐
- vector迭代器
https://www.cnblogs.com/quant-lee/p/6618829.html
- moment.js获取本周本月本年的开始日期和结束日期
//获取本日 const startDate = moment().format('YYYY-MM-DD'); const startDate = moment().format('YYYY-MM-D ...
- NodeJS学习笔记 (7)网络服务-http-client(ok)
原文:https://github.com/chyingp/nodejs-learning-guide 自己敲代码: ClientRequest概览 当你调用 http.request(options ...
- /etc/rc.d/rc.sysinit
[root@web02 ~]# ls /etc/rc.d/rc.sysinit /etc/rc.d/rc.sysinit [root@web02 ~]# [root@web02 ~]# ls /etc ...
- HISTFILESIZE与HISTSIZE的区别
在linux系统中,history命令可以输出历史命令,历史命令默认保存在文件~/.bash_history中. HISTFILESIZE 与 HISTSIZE都是history命令需要用到的两个sh ...
- shell的通俗理解
(引自:https://zhidao.baidu.com/question/557066905.html) [一] shell的含义: 首先shell的英文含义是“壳”: 它是相对于内核来说的,因为它 ...
- 【BZOJ 1483】[HNOI2009]梦幻布丁
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 链表,启发式合并. 把x变成y,和y全都变成x. 不论是前者还是后者.连续段的个数都是相同的,不影响结果. 那么我们把x,y中出现次 ...
- 洛谷 P1275 魔板
P1275 魔板 题目描述 有这样一种魔板:它是一个长方形的面板,被划分成n行m列的n*m个方格.每个方格内有一个小灯泡,灯泡的状态有两种(亮或暗).我们可以通过若干操作使魔板从一个状态改变为另一个状 ...
- js 动画1
div速度 运动: 代码例如以下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " ...
- Bootstrap组件之输入框组
.input-group--设置div为输入框组: .input-group-lg..input-group-sm..input-group-xs--改变输入框组的尺寸: .input-group-a ...