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

   

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值