differences between new and malloc in c++ [duplica

2019-09-22 04:51发布

This question already has an answer here:

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

2条回答
趁早两清
2楼-- · 2019-09-22 05:22

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

查看更多
等我变得足够好
3楼-- · 2019-09-22 05:25

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.

查看更多
登录 后发表回答