类具有虚函数和可访问的非虚析构函数
我有两个类:
class A {
public:
virtual void somefunction() = 0;
};
class B : public A {
public:
B();
~B();
void somefunction();
};
B::B() {}
void B::somefunction() {
// some code
}
但是使用 g++ 我收到错误:
class A has virtual functions and accessible non-virtual destructor
class B has virtual functions and accessible non-virtual destructor
我不知道这个错误是什么......我在博客上的某个地方读到这是一个编译器警告。我该如何解决这个问题?
I have two classes:
class A {
public:
virtual void somefunction() = 0;
};
class B : public A {
public:
B();
~B();
void somefunction();
};
B::B() {}
void B::somefunction() {
// some code
}
But with g++ I get errors:
class A has virtual functions and accessible non-virtual destructor
class B has virtual functions and accessible non-virtual destructor
I don't have any idea what this error is... Somewhere on blogs I read that it's a compiler warning. How can I fix the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
发生这种情况是因为您的基类 A 没有虚拟析构函数。例如,如果您有以下代码:
那么
delete a
调用将无法调用B
的析构函数,因为A
的析构函数不是不是虚拟的。 (这会泄漏B
的所有资源。)您可以了解更多信息关于虚拟析构函数在这里。将虚拟析构函数添加到您的基类中,您应该没问题。
This happens because your base class
A
does not have a virtual destructor. For instance, if you had this code:Then the
delete a
call would not be able to callB
's destructor becauseA
's isn't virtual. (It would leak all ofB
's resources.) You can read more about virtual destructors here.Add a virtual destructor to your base class and you should be fine.
指定类 A:
这样,如果您通过
A*
删除派生类(例如 B),它们的自定义析构函数仍然会被调用。Give class A:
That way, derived classes such as B will still have their custom destructor called if you
delete
them via anA*
.作为经验法则(恕我直言)或简而言之,基类中的析构函数必须是公共和虚拟的或受保护的非虚拟,以防止内存泄漏。通过这样做,析构函数派生类的 > 被调用,这样每当删除保存派生地址/引用的基指针/引用时,就可以防止内存泄漏。
As thumb rule(IMHO) or in Short the destructor in the base class has to be either public and virtual or protected non virtual to prevent the memory leaks.by doing so the destructors of the derived class get called and this prevents the memory leakage whenever the Base pointer/reference holding derived address/reference is deleted.
如果一个类有虚函数,那么它的析构函数也应该是虚的。你的析构函数有一个可访问的析构函数,但它不是虚拟的。
If a class has virtual functions then its destructor should be virtual as well. Yours has an accessible destructor but it is not virtual.