1.malloc和free是库函数,以字节为单位申请内存
2.new和delete是关键字,以类型为单位申请内存
3.malloc和free单纯的对内存进行申请与释放
4.对于基本类型new关键字会对内存进行初始化
5.对于类类型new和delete还负责构造函数和析构函数的调用
class Test { private: int i; public: Test() { cout << "Test()" << endl; i=0; } Test(int i) { cout << "Test(int i)" << endl; this->i=i; } ~Test() { cout << "~Test()" << endl; } int getI() { return i; } };
void func() { int *p = reinterpret_cast<int*>(malloc(sizeof(int))); //malloc不能直接初始化 int *q = new int(10); //(new可以申请内存的时候初始化) *p = 5; cout << *p << " " << *q << endl; free(p); delete q; Test* tp = reinterpret_cast<Test*>(malloc(sizeof(int))); Test* tq = new Test; cout << tp->getI() << " " << tq->getI() << endl; free(tp); delete tq; } example: 请问count是多少? class A { private: static int c_count; public: A() { c_count++; } ~A() { c_count--; } static void Count() { cout <<c_count<<endl; } }; int A::c_count = 0; int main() { A* a = static_cast<A*>(malloc(sizeof(A))); //由于只是申请一段内存,对象没有生成, a->Count(); //所以没有调用构造函数,c_count保持为0 delete a; //调用delete函数后,析构函数会被调用,c_count--, a->Count(); c_count会变为-1 return 0; }