differences between new and malloc in c++ -
this question has answer here:
- in cases use malloc vs new? 18 answers
#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 when use 'new' constructor printed out when simple derefrence pointer myboxarray2 constructor not printed , neither funtion printer printed. why when use -> funnction printer runs not when use equivalent *(myboxarray2).printer(23)
malloc allocates memory only, doesn't invoke constructors can leave objects in indeterminate state.
in c++ should never use malloc, calloc or free. , if possible avoid new , new[] well, use object instances or vectors of instances instead.
as second question (which unrelated first), *(myboxarray2).printer(23) wrong since the . selection operator have higher precedence dereference operator *. means first of use . member selector on pointer invalid, , attempt dereference printer returns wrong since doesn't return anything.
you want (*myboxarray2).printer(23) (note location of asterisk inside parentheses), exactly same myboxarray2->printer(23).
also note myboxarray2->printer(23) same myboxarray2[0].printer(23).
Comments
Post a Comment