C++11 – 父类与子类相互包含的时候该如何正确的使用智能指针,防止循环引用
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++11 – 父类与子类相互包含的时候该如何正确的使用智能指针,防止循环引用
原文链接:https://www.stubbornhuang.com/918/
发布于:2020年09月25日 11:18:10
修改于:2020年10月31日 16:43:45
1 父类和子类相互包含的应用场景
在实际开发的过程中,经常会遇到这种类似的问题,一个父类通常维护着属于该父类的多个子类指针,而每一个子类中也存储着指向其父类的指针对象,方便进行节点递归或者其他操作。
比如说:
一个三维立方体,每一个三维立方体类都包含了所有属于该立方体的三角面类,而每一个三角面都存储着指向包含该三角面的三维立方体指针。
这种父类和子类都相互存储着指向互相指针,这种情况下很容易出现循环引用而导致内存泄漏的问题,那么我们该如何正确的使用std::weak_ptr去解决这种应用场景的问题呢?
2 代码示例
可以参考以下代码去优化自己的实际用例:
#include <vld.h>
#include <iostream>
#include <functional>
#include <memory>
#include <vector>
using namespace std;
class Child;
class Parent
{
public:
typedef std::shared_ptr<Parent> ptr;
Parent()
{
}
virtual ~Parent()
{
}
void AddChild(std::shared_ptr<Child> childPtr)
{
m_pChildPtrVector.push_back(childPtr);
}
private:
std::vector<std::shared_ptr<Child>> m_pChildPtrVector;
};
class Child
{
public:
typedef std::shared_ptr<Child> ptr;
Child()
{
}
virtual~Child()
{
}
void SetParent(std::weak_ptr<Parent> parentPtr)
{
m_pParentPtr = parentPtr;
}
private:
std::weak_ptr<Parent> m_pParentPtr;
};
int main()
{
Parent::ptr parent = std::make_shared<Parent>();
for (int i = 0;i < 50; ++i)
{
Child::ptr childPtr = std::make_shared<Child>();
childPtr->SetParent(parent);
parent->AddChild(childPtr);
}
getchar();
return 0;
}
当前分类随机文章推荐
- C++ - vector存储动态指针时正确释放内存 阅读5902次,点赞0次
- C++ - 我的代码风格/代码规范备忘 阅读910次,点赞0次
- C++ - 使用宏区分不同系统平台、不同编译器、不同编译模式等编译期宏使用总结 阅读1404次,点赞0次
- C++ - 拷贝构造函数与拷贝构造函数调用时机 阅读392次,点赞0次
- C++ - Windows下字符串UTF8编码转ANSI,ANSI转UTF8编码 阅读509次,点赞0次
- CMake - 设置Debug或者Release编译模式 阅读2893次,点赞0次
- C++11 - 使用std::thread在类内部以成员函数作为多线程函数执行异步操作 阅读2632次,点赞0次
- C++ - Windows获取电脑上摄像头设备数目、名字以及id 阅读466次,点赞0次
- C++读取Shp文件并将Shp转化为DXF 阅读3225次,点赞1次
- C++ - 获取当前进程内存使用情况 阅读9137次,点赞10次
全站随机文章推荐
- 资源分享 - Practical Linear Algebra - A Geometry Toolbox , First Edition 英文高清PDF下载 阅读1374次,点赞0次
- GCC/GG++中编译优化选项-O -O0 -O1 -O2 -O3 -Os -Ofast -Og -Oz各自的区别和作用 阅读4017次,点赞3次
- 我的Windows装机必备软件备忘 阅读335次,点赞0次
- 杂谈 - 2022年度总结 阅读330次,点赞0次
- 书籍翻译 – Fundamentals of Computer Graphics, Fourth Edition,第12章 Data Structures for Graphics中文翻译 阅读1326次,点赞4次
- Python - 深度学习训练过程使用matplotlib.pyplot实时动态显示loss和acc曲线 阅读2400次,点赞0次
- 资源分享 - Principles of Digital Image Synthesis , Volume 1 and Volume 2 英文高清PDF下载 阅读1645次,点赞0次
- 资源分享 - GPU Pro 360 - Guide to Image Space 英文高清PDF下载 阅读2055次,点赞1次
- Duilib - RichEdit和List等控件增加垂直滚动条vscrollbar和水平滚动条hscrollbar 阅读1669次,点赞2次
- Python - 使用Python+websockets时报错:AttributeError: module 'websockets' has no attribute 'serve' 阅读1617次,点赞0次
评论
169