智能指针的优缺点 [英] pros and cons of smart pointers

查看:121
本文介绍了智能指针的优缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道智能指针用于资源管理并支持RAII.

I came to know that smart pointer is used for resource management and supports RAII.

但是在什么情况下,智能指针似乎并不智能,使用时要记住什么呢?

But what are the corner cases in which smart pointer doesn't seem smart and things to be kept in mind while using it ?

推荐答案

智能指针无助于防止图形结构中的循环.

Smart pointers don't help against loops in graph-like structures.

例如,对象A拥有指向对象B的智能指针,而对象B则拥有指向对象A的智能指针.如果在断开A与B的连接(或从A断开B的连接)之前释放了指向A和B的所有指针,则A和B都会互相抱着,形成快乐的记忆泄漏.

For example, object A holds a smart pointer to object B and object B - back to object A. If you release all pointers to both A and B before disconnection A from B (or B from A) both A and B will hold each other and form a happy memory leak.

垃圾回收可以帮助解决这一问题-它可以看到两个对象都无法到达并释放它们.

Garbage collection could help against that - it could see that both object are unreachable and free them.

这篇关于智能指针的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆