new、delete、malloc、free 在堆栈上的使用区别 C++
生活随笔
收集整理的這篇文章主要介紹了
new、delete、malloc、free 在堆栈上的使用区别 C++
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
int a[10] = { 0 } // 這是在棧中的
int b[10] = malloc(sizeof(int) * 10); // 這是在堆中的
malloc和free是函數(shù),是標(biāo)準(zhǔn)庫stdio中的
new和delete是關(guān)鍵字
new在堆上初始化一個(gè)對(duì)象的時(shí)候,會(huì)調(diào)用構(gòu)造函數(shù)。 malloc不會(huì)。
delete使用之前,會(huì)調(diào)用對(duì)象的析構(gòu)函數(shù),再釋放。 ?free不會(huì)調(diào)用析構(gòu)。
?
#if 0 //數(shù)組在堆中還是在棧中 int a[10] = { 0 } // 這是在棧中的 int b[10] = malloc(sizeof(int) * 10); // 這是在堆中的 malloc和free是函數(shù),是標(biāo)準(zhǔn)庫stdio中的 new和delete是關(guān)鍵字 new在堆上初始化一個(gè)對(duì)象的時(shí)候,會(huì)調(diào)用構(gòu)造函數(shù)。 malloc不會(huì)。 delete使用之前,會(huì)調(diào)用對(duì)象的析構(gòu)函數(shù),再釋放。 free不會(huì)調(diào)用析構(gòu)。 #endif#define _CRT_SECURE_NO_WARNINGS#include <iostream> using namespace std;//在堆上 開辟內(nèi)存空間// 開辟一個(gè)字節(jié) //C語言中 void test1() {int* p = (int*)malloc(sizeof(int));*p = 10; //使用printf("C:%d", *p);printf("\n");if (p != NULL){free(p);p = NULL;}}//C++語言中 void test2() {int* p = new int;*p = 2; //使用cout << "C++:" << *p << endl;if (p != NULL){delete p;p = NULL;}}// 開辟一個(gè)數(shù)組 //C語言中 void test3(int num) {int* arr_p = (int*)malloc(sizeof(int)*num);//賦值使用for (int i = 0; i < num; i++){arr_p[i] = i+1;}//打印for (int i = 0; i < num; i++){printf("%d,",arr_p[i]);}printf("\n");//釋放if (arr_p != NULL){free(arr_p);arr_p = NULL;} }//C++語言中 void test4(int num) {int* arr_p = new int[num];//賦值使用for (int i = 0; i < num; i++){arr_p[i] = i + 1;}//打印for (int i = 0; i < num; i++){cout << arr_p[i] << "," ;}cout << endl;//釋放if (arr_p != NULL){delete[] arr_p;arr_p = NULL;} }class Test { public:Test(int id,const char* name){m_id = id;int len = strlen(name);m_name = (char*)malloc(len + 1);strcpy(m_name, name); cout<<"Test()"<<endl;}void printT(){cout << "m_id=" << m_id << ",m_name=" << *m_name << endl;}~Test(){cout << "~Test()" << endl;} private:int m_id;char *m_name; };void test5() {Test* tp = (Test*)malloc(sizeof(Test));tp->printT(); //錯(cuò)誤,因?yàn)閠p指向的對(duì)象在創(chuàng)建的時(shí)候沒有初始化值,沒有可以打印的值if (tp != NULL){free(tp);tp = NULL;} } void test6() {Test* tp = new Test(10,"zhangsan"); //創(chuàng)建的時(shí)候,就調(diào)用了構(gòu)造函數(shù)tp->printT();if (tp != NULL){delete tp;tp = NULL;} }int main() {test1();test2();test3(10);test4(10);cout << "--------" << endl;//test5();cout << "--------" << endl;test6();return 0; }?
?
總結(jié)
以上是生活随笔為你收集整理的new、delete、malloc、free 在堆栈上的使用区别 C++的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: namespace命名空间的理解C++
- 下一篇: static 静态成员变量和静态函数 C