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