在c++中,通知引用对象被删除
Informing the referencing object that the referred one is deleted in C++
我想问以下问题:
假设c++中有三个类:A、B和C。A类的对象创建并拥有B类的对象,然后将B类的引用作为指针变量存储给C类的对象。那么,如果A被删除,通知C指向B的指针不再有效(并且应该设置为null)的最佳实践是什么?
是否有一个通用的方法或例如一个特定的Qt ?
使用std::weak_ptr
示例(现场演示)
class A
{
private:
std::shared_ptr<B> myB;
public:
A() :
myB(std::make_shared<B>())
{
}
std::weak_ptr<B> GetB()
{
return myB;
}
};
class B
{
};
class C
{
private:
std::weak_ptr<B> theB;
public:
C(std::weak_ptr<B> b) :
theB(b)
{
}
void test()
{
auto b = theB.lock();
if (b)
{
// theB is still valid
}
else
{
// theB is gone
}
}
};
相关文章:
- 线程调用的函数对对象删除是否安全?
- 当我使用dynamic_cast并删除对象删除时,析构函数是如何工作的?
- 使用 com 对象删除计划任务
- C 将对象删除为参考
- C样式对象删除的包装器
- 静态映射中动态分配的对象.删除必要的
- C++指向对象删除的指针数组,"Debug assertion failure!"
- 在其成员函数返回之前,将对象删除是不确定的行为吗?
- Python 对象删除检测
- C++安全对象删除
- Qt:RemoveWidget和对象删除
- Qt对象删除导致崩溃
- 删除由两个shared_pointer实例管理的对象(删除其中一个)
- 顶点缓冲区对象(删除进程)opengl
- 设计 -- 按名称或对象删除
- 提升中的异常:进程间,共享内存对象删除
- 使用std::function和std::bind来存储回调并处理对象删除
- 如何使用智能指针防止双重对象删除
- 指针指向对象删除时自动为空
- 对象层次结构中的对象删除责任