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>头文件中 局部变量由于存储在栈中,一旦离开函数,变量就会被释放,当我们需要将数据持久使用,就需要将数据保存到堆中,而在堆中申请内存空间就需 ...
随机推荐
- 洛谷P3254 圆桌问题 网络流_二分图
Code: #include<cstdio> #include<algorithm> #include<vector> #include<queue> ...
- 路飞学城Python-Day16
- C语言静态库与动态库(Windows下测试)
转载于:https://zhidao.baidu.com/question/1946953913764139388.html,原文为Linux上测试,本文为在Windows上编译测试 我们通常把一些公 ...
- [HDU5685]2016"百度之星" - 资格赛 Problem A
题目大意:给你一个字符串,和一些问题,每个问题问你[l,r]子串的哈希值是多少. 哈希值计算方法为:$H(s)=\prod _{i=1} ^{i\leq len(s)}(s_i-28)(mod\ 99 ...
- 浅谈python 中正则的一些函数
主要的函数有 : match() search() findall() group() groups() split() match (): 含义 开头匹配,匹配成功返回一个对象失败则 ...
- oracle数据库回滚
线下测试数据误操作,回滚攻略--把数据捞出来,这个时间自己设置--表名一定要是:xx_tbd日期 CREATE TABLE user_tbd0718ASselect * from user as of ...
- 本地yum源安装docker
Directory listing for / audit-libs-python-2.7.6-3.el7.x86_64.rpm checkpolicy-2.5-4.el7.x86_64.rpm co ...
- [Javascript] Simplify Creating Immutable Data Trees With Immer
Immer is a tiny library that makes it possible to work with immutable data in JavaScript in a much m ...
- Querying mergeinfo requires version 3 of the FSFS filesystem schema svn右键没菜单
svn 报错,Querying mergeinfo requires version 3 of the FSFS filesystem schema 经过查询,是svn客户端和服务端版本不一致造成的. ...
- Effective JavaScript Item 34 在prototype上保存方法
本系列作为EffectiveJavaScript的读书笔记. 不使用prototype进行JavaScript的编码是全然可行的,比如: function User(name, passwordHas ...