C++动态内存和智能指针
原文链接:https://blog.csdn.net/qq_39355828/article/details/110841345 (opens new window)
# 动态内存和智能指针
# 1.智能指针
#include
Shared_ptrp1;//指向string
Shared_ptrp2;//指向int的list
shared_ptr允许多个指针指向同一个对象,unique则是独占所指向的对象,weak_ptr是一种弱引用,指向shared_ptr管理的对象。他们都定义在memory头文件中
unique_ptr -single ownership//独享对象
shared_ptr//-共享智能指针
weak_ptr://弱指针
auto e1=std::make_unique();
void bar(Entity *e)
{
}
void foo()
{
Entity*e =new Entity();
e->do somethings();
bar(e)
}//容易造成内存泄漏,没有删除e
--
auto e1=std::make_shared<Entity>();
std::weak_ptr<Entity>ew=e1
if(std::shared_ptr<Entity>e2=ew.lock())
e2->DoSomething
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 2.动态内存
C++用new来分配堆空间,delete删除堆空间
Int *p=malloc(sizeof(int)),int *p=999;
Int *p=new int;
Int *p=new int(999);
delete p;//进行删除
–
Int p=malloc(10sizeof(int));
Int *p=new int[10];
delete[]p;
圆括号中是数字,方括号是表示大小。
有多个被分配需要用中括号进行删除delete
编辑 (opens new window)
上次更新: 2026/08/11, 13:36:18