Gnuhpc
Source: http://www.cnblogs.com/gnuhpc/
A few days ago a friend to interview Baidu Space of a post, was asked this question, I listen to say a few points, but the feeling is still not thorough, so the Internet access to some information, I think again, summed up.
- Different actions:
- In C + +, when new is an object, the program finishes allocating space for the object while the constructor is called, similar to delete an object, the object's space is freed while the destructor is also called.
- In C, malloc and free do not have constructors or destructors called this action. Of course, in the absence of a specific constructor or destructor, C + + does not have this action.
- About overloading:
- In C + +, for any non-array space allocation, we can do overloading the constructors by defining constructors with the same name but different arguments, and for the space allocation of the array, only the default constructor is used, and if you attempt to open an array without a default constructor, compiler will make an error.
- In C, nature is not overloaded with this thing.
- The return value is different:
- In C, malloc returns a void * pointer that requires you to force the pointer type conversion
- In C + +, you are just as good as the new one.
- Note that for basic types, this difference is the only difference, and of course it is not recommended to use malloc+ in C + + to force type conversions to create basic data types or objects.
- Different definitions:
- New is an operator
- malloc is a function
- Exception handling methods are different:
- New throws an exception
- malloc returns null
- Allocation space units are different:
- The new allocation unit is a multiple of the space occupied by the object.
- malloc is byte
Tips for use:
Improper use of 1.delete can cause memory leaks, and the following example is where only the first T is released:
test* t = new test[3];
Delete T;
The following code can cause heap crashes or data loss.
test* t = new Test; Delete[] t; <--This is even worse
2.realloc can only be used for malloc. In C + + you can only re-open space, copy, and release the original space to do the same thing.
3. Performance differences, according to http://code.dawnofthegeeks.com/2009/05/04/fyi-new-vs-malloc/which refers to malloc/free slower than New/delete, But in the later I developed a program, but there are different scenes.
Ext.: http://www.cnblogs.com/gnuhpc/archive/2012/12/10/2811943.html
"Go" in C + + in the new VS C language of malloc