differences between new and malloc in c++ [duplicate]

做~自己de王妃 提交于 2019-12-13 23:18:55

问题


#include <iostream>
#include <cstdlib>
using namespace std;

class Box {
   public:
      Box() {
         cout << "Constructor called!" <<endl;
      }
      void printer(int x)
    {
        cout<<x<<" printer"<<endl;
    }

      ~Box() {
         cout << "Destructor called!" <<endl;
      }

};

int main( ) {
    Box* myBoxArray = new Box[4];

    Box* myBoxArray2 = (Box*)malloc(sizeof(Box[4]));
    myBoxArray2->printer(23);
    *myBoxArray2;
    *(myBoxArray2).printer(23);

   return 0;
}

the problem simply is that when i use 'new' the constructor is printed out but when i simple derefrence the pointer to myBoxArray2 the constructor is not printed and neither is the funtion printer printed. Also why is it that when i use -> the funnction printer runs but not when i use the equivalent *(myBoxArray2).printer(23)


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/43272619/differences-between-new-and-malloc-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!