我有一個非常奇怪的問題,我希望有人遇到過。在析構函數中調用成員變量的虛函數會導致seg錯誤
class Letter
{
public:
Letter()
virtual ~Letter()
virtual std::string get() const = 0;
};
class A : public Letter
{
public:
A()
~A()
virtual std::string get() const { return "A"; }
};
class Board
{
public:
Board(){}
~Board()
{
std::cout << "Removing: " << letter->get() << std::endl;
delete letter;
}
void setLetter(Letter * l) { letter = l }
private:
Letter * letter;
}
int main()
{
Board b;
b.setLetter(new A());
}
該程序使得賽格故障時局超出範圍在哪裏)的虛擬功能信紙>得到(被稱爲在析構函數的行。我正在使用gcc 4.1.2。有任何想法嗎?
UPDATE
好,似乎所發生的情況在實際的代碼是這樣的等價的:
class Board
{
public:
Board(){}
~Board()
{
std::cout << "Removing: " << letter->get() << std::endl;
}
void setLetter(Letter * l) { letter = l; }
private:
Letter* letter;
};
int main()
{
Board b;
A a;
b.setLetter(&a);
return 0;
}
在這種情況下,已經超出了範圍,當虛函數被調用。
是不是〜Letter()或〜A()做了什麼? –
你能提供一個重現錯誤並實際編譯的最小例子嗎?我修正了你的代碼片段中的錯誤,並且運行正常。 –
嘗試在聲明後加上一些分號......可能會這樣做。 –