c/c++ new delete初探

new delete初探

1,new有2个作用

  • 开辟内存空间。
  • 调用构造函数。

2,delete也有2个作用

  • 释放内存空间
  • 调用析构函数。

如果用new开辟一个类的对象的数组,这个类里必须有默认(没有参数的构造函数,或者有默认值的参数的构造函数)的构造函数。

释放数组时,必须加[]。delete []p

也可以用malloc,free,但是malloc不会自动调用类的构造函数,free也不会自动调用类的析构函数。

include <iostream>
#include <malloc.h>

using namespace std;

void c_1(){
  //c方式的内存空间的动态开辟                                   
  int n;
  cin >> n;
  int *p = (int*)malloc(sizeof(int) * n);
  for(int i = 0; i < n ; ++i){
    p[i] = i;
  }
  free(p);
}

void cpp_1(){
  //c++方式的内存空间的动态开辟                                 
  int m;
  cin >> m;
  int *q = new int[m];
  for(int i = 0; i < m ; ++i){
    q[i] = i;
  }
  //释放数组的空间,要加[]                                      
  delete []q;
}

class Test{
public:
  Test(int d = 0) : data(d){
    cout << "create" << endl;
  }
  ~Test(){
    cout << "free" << endl;
  }
private:
  int data;
};

void c_2(){
  Test *t = (Test*)malloc(sizeof(Test));
  free(t);
}
void cpp_2(){
  Test *t = new Test(10);
  delete t;
}
int main(){
  c_1();
  cpp_1();

  c_2();
  cpp_2();
                                                               
  Test *t = new Test[3];                                        
  delete []t;                                                   
                                                                
  return 0;                                                     
} 

转载于:https://www.cnblogs.com/xiaoshiwang/p/9509183.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值