【发布时间】:2011-06-04 11:56:21
【问题描述】:
我了解派生类与其基类的指针类型兼容。在给定的示例代码中,new bar 对象构造发生在调用foo::foo() 后跟bar::bar()。在各自的构造函数中,我将资源分配给类成员foo::int *a 和bar::int *b。
现在我将这样构造的对象初始化为基类类型。使用obj,我可以调用基类析构函数,但不能调用派生类析构函数。那么,在这种情况下如何释放派生类资源呢?这不是内存泄漏吗?
#include <iostream>
class foo
{
int *a;
public:
foo()
{
a = new int[5];
std::cout << "\n foo constructor" << std::endl;
}
~foo()
{
std::cout << "\n foo destructor" << std::endl;
delete[] a;
}
};
class bar : public foo
{
int *b;
public:
bar()
{
b = new int[5];
std::cout << "\n bar constructor" << std::endl;
}
~bar()
{
std::cout << "\n bar destructor" << std::endl;
delete[] b;
}
};
int main()
{
foo *obj = new bar; // Derived class object is type compatible with base class
delete obj; // Equivalent to obj->~foo();
return 0;
}
谢谢。
【问题讨论】:
-
请注意,在实际代码中,对于任何管理资源的类,都必须遵循三法则,并声明析构函数、复制构造函数和复制赋值运算符。
标签: c++ constructor destructor