C++内存管理
c 语言中提供了 malloc 和 free 两个系统函数,完成对堆内存的申请和释放。而 c++则
提供了两关键字 new 和 delete ;
new/delete
new/new[]用法:
int *p = new int; //开辟大小为 sizeof(int)空间
int *a = new int(5); //开辟大小为 sizeof(int)空间,并初始化为 5
// todo new/delete
#include <iostream> //<iostream>
using namespace std; //
int main() {
//单变量
int *p=new int(20);
cout<<*p<<endl; //20
*p=10;
cout<<*p<<endl; //10
string *s=new string("hello");
cout<<*s<<endl; //hello
*s="world";
cout<<*s<<endl; //world
struct Sut{
int age;
string name;
};
Sut* s1=new Sut;
s1->age=20;
s1->name="Tom";
cout<<s1->age<<en