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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM