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