前言:
此刻朋友们对“vs2017怎么运行c语言代码”大概比较关怀,朋友们都需要分析一些“vs2017怎么运行c语言代码”的相关文章。那么小编也在网络上收集了一些关于“vs2017怎么运行c语言代码””的相关资讯,希望姐妹们能喜欢,看官们快快来学习一下吧!起因
最初学习C++是想知道.Net CLR内部是如何实现.对C++的学习是没有系统性的学习.不过还好是认识到资源的释放,从手动到半自动(C语言到C++)资源释放.这一点和C#/Java是不一样的.因为这两个都GC(垃圾回收).
该文是迁移过来的,代码是在VS2017下运行的.
new/delete 与 malloc/free 区别
相同点:
对于基本数据类型,分配和释放是一致的.都不可以多次释放.free不改变指针的值,delete会改变.
不同点:
malloc不会调用构造函数,free不会调用析构函数.相同点 示例
#include <iostream>using namespace std;int main(int argc, char *argv[]){ //malloc/free int *p1 = (int*)malloc(sizeof(int)); *p1 = 888; cout << "p1地址:" << p1 << " p1值:" << *p1 << endl; free(p1); cout << "free p1地址:" << p1 << " free p1值:" << *p1 << endl; int *p2 = new int(888); cout << "p2地址:" << p2 << " p2值:" << *p2 << endl; delete p2; //应该在delete之后,将指针指向nullptr,不能多次delete cout << "delete p2地址:" << p2 << " delete p1值:" << *p1 << endl; //free之后,应该将指针指向NULL p1 = NULL; //delete之后,应该将指针指向nullptr p2 = nullptr; cin.get(); return 0;}
不同点 示例
#include <iostream>using namespace std;class People{public: People() { cout << "create people" << endl; } ~People() { cout << "dispose people" << endl; }private:};//malloc/free 在c++中,使用malloc不会触发构造函数,使用free释放不会触发析构函数int main(int argc, char *argv[]){ cout << "执行开始" << endl; People *p1 = (People*)malloc(sizeof(People)); free(p1); cout << "执行结束" << endl; cin.get(); return 0;}
#include <iostream>using namespace std;class People{private: char *p;public: People() { p = (char*)malloc(sizeof(char) * 1024 * 1024 * 128); //分配128兆空间 cout << "create people" << endl; } ~People() { delete p; //释放空间 cout << "dispose people" << endl; }};int main(int argc, char *argv[]){ People *people(new People); delete people; //单个对象用delete去释放 cin.get(); return 0;}
在new分配实例的时候,触发构造函数,并进行分配128兆空间
在delete释放实例之后,触发析构函数,并把在构造函数的分配的内存进行释放
delete使用注意事项
#include <iostream>using namespace std;class People{private: char *p;public: People() { p = (char*)malloc(sizeof(char) * 1024 * 1024 * 128); //分配128兆空间 cout << "create people" << endl; } ~People() { delete p; //释放空间 cout << "dispose people" << endl; }};int main(int argc, char *argv[]){ //对于基本数据类型数组,delete与delete[]作用一样 int *p = new int[10]{ 1,2,3,4,5,6,7,8,9,0 }; //delete p; delete[] p; //对于符合类型,单个对象用delete去释放,对象数组用delete[]去释放 People *people(new People); delete people; //单个对象用delete去释放 //delete[]释放单个对象,会一直调用析构函数,进行释放 //delete[] people; cin.get(); return 0;}
如果您觉得对您有用的话,可以点个赞或者加个关注,欢迎大家一起进行技术交流
标签: #vs2017怎么运行c语言代码 #new分配的内存空间