1. 程式人生 > >malloc,free和new delete的區別

malloc,free和new delete的區別

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;
}