我开始自学 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 的内存?