[英]What does 'has virtual method … but non-virtual destructor' warning mean during C++ compilation?
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
virtual int area ()
{ return (0); }
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
};
有匯編警告
Class '[C@1a9e0f7' has virtual method 'area' but non-virtual destructor
如何理解這個警告以及如何改進代碼?
[編輯]這個版本現在正確嗎? (試圖回答用這個概念來闡明自己)
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
virtual ~CPolygon(){};
virtual int area ()
{ return (0); }
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
~CRectangle(){}
};
如果一個類有一個虛方法,那就意味着你希望其他類繼承它。 這些類可以通過基類引用或指針銷毀,但這只有在基類具有虛擬析構函數時才有效。 如果你有一個應該是多態的類,那么它也應該是多態的可刪除的。
這個問題在這里也得到了深入的回答。 以下是演示效果的完整示例程序:
#include <iostream>
class FooBase {
public:
~FooBase() { std::cout << "Destructor of FooBase" << std::endl; }
};
class Foo : public FooBase {
public:
~Foo() { std::cout << "Destructor of Foo" << std::endl; }
};
class BarBase {
public:
virtual ~BarBase() { std::cout << "Destructor of BarBase" << std::endl; }
};
class Bar : public BarBase {
public:
~Bar() { std::cout << "Destructor of Bar" << std::endl; }
};
int main() {
FooBase * foo = new Foo;
delete foo; // deletes only FooBase-part of Foo-object;
BarBase * bar = new Bar;
delete bar; // deletes complete object
}
輸出:
Destructor of FooBase
Destructor of Bar
Destructor of BarBase
注意delete bar;
導致兩個析構函數~Bar
和~BarBase
被調用,而delete foo;
只調用~FooBase
。 后者甚至是未定義的行為 ,因此不能保證這種效果。
這意味着您需要使用虛方法在基類上使用虛擬析構函數。
struct Foo {
virtual ~Foo() {}
virtual void bar() = 0;
};
離開它關閉
是
可能會導致不確定的行為,往往表現為在像Valgrind的工具內存泄漏。
它只是意味着像一個代碼
CPolygon* p = new CRectangle;
delete p;
...或任何包裝到智能指針中的任何東西,基本上都不會正常運行,因為CPolygon在刪除時不是多態的,並且CRectange部分不會被正確銷毀。
如果您不打算刪除CRectangle和CPolygon的多態,那么該警告沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.