确保c++对象被正确地解分配

Ensuring C++ Object is properly de-allocated

本文关键字:分配 正确地 c++ 对象 确保      更新时间:2023-10-16

我开始自学c++,如何在没有垃圾收集器的情况下处理对象,这让我感到有些困惑。下面是我要做的一个简单的例子:

A* a;
B b = new B(a);    // Note that B is a derived class of A
a = &b;
while (a != NULL)
{
    (*a).run();
}

这一切都像我期望的那样工作。我遇到的问题是,在B的run()方法中,我想做这样的事情:

C c = new C(a);  // a is the same pointer as above, that has been stored 
                 // and C another derived class from A
a = &c;

然后让run()退出。然后,第一个块中的while循环将在新对象上调用run()。我的问题是,我如何确保原始b的内存被正确地解除分配?

在这种情况下可以使用std::shared_ptr。如果两个类的成员需要指向同一个对象,那么可以将它们都设置为shared_ptr。你通常这样做,但是如果在这样做的时候,如果你要创建循环依赖,那么打破这个循环依赖,你需要std::weak_ptr

下面是std::shared_ptrstd::weak_ptr的例子。

错误代码(循环依赖):

struct B;
struct A
{
   std::shared_ptr<B> bp;
}
struct B
{
   std::shared_ptr<A> ba;  //this creates a cyclic dependency.
}
正确代码(非循环):
struct B;
struct A
{
   std::shared_ptr<B> bp;
}
struct B
{
   std::weak_ptr<A> ba;  //break cyclic dependency with std::weak_ptr
}

当你面对动态内存分配和重要的所有权语义时,智能指针通常是确保正确性的好方法。

参见std::shared_ptr