differences between new and malloc in c++

This question already has an answer here:

  • In what cases do I use malloc vs new? 18 answers

  • malloc allocates memory only, it doesn't invoke constructors which can leave objects in an indeterminate state.

    In C++ you should almost never use malloc , calloc or free . And if possible avoid new and new[] as well, use object instances or vectors of instances instead.


    As for your second question (which is really unrelated to the first), *(myBoxArray2).printer(23) is wrong since the the . selection operator have higher precedence than the dereference operator * . That means first of all that you use the . member selector on a pointer which is invalid, and that you attempt to dereference what printer returns which is also wrong since it doesn't return anything.

    You want (*myBoxArray2).printer(23) (note the location of the asterisk is inside the parentheses), which is exactly the same as myBoxArray2->printer(23) .

    Also note that myBoxArray2->printer(23) is the same as myBoxArray2[0].printer(23) .


    The difference is that malloc allocates memory without initializing it at all. On the other hand, new calls the appropriate constructor to initialize that memory (if that constructor is made to initialize that memory) and do other stuff to make a class usable.

    Also delete calls the destructor for you.

    Rule of thumb is: Never use malloc with C++, unless you know what you're doing.

    链接地址: http://www.djcxy.com/p/78486.html

    上一篇: 动态分配'串'数组

    下一篇: new和malloc在c ++中的区别