I所述使用MS Visual Studio 2010中調用同一對象多次的析構函數,如在標準
我製成實施雙鏈表的結果是不相同的。
我想知道爲什麼在調用方法Clean後,在調用對象的析構函數後,在引用該對象之後,不會引發任何錯誤。
下面是我的一些雙鏈表的方法(相對於我的問題):
/*DoubleLinkedList.cpp */
DoubleLinkedList::~DoubleLinkedList(void)
{
cout << "Destructor invoked" << endl;
// as for data nodes memory is allocated in heap we have to release it:
const Node* const_iterator = m_head.m_next;
while (const_iterator != &m_tail)
{
const_iterator = const_iterator->m_next;
delete const_iterator->m_prev;
}
}
void DoubleLinkedList::Clean(void)
{
cout << "Clean invoked" << endl;
this->~DoubleLinkedList(); /* According to C++ 11 standart: Once a destructor is invoked for an object, the object no longer exists*/
}
/* main.cpp */
int main(int argc, char* argv[])
{
DoubleLinkedList list;
Circle c1, c2(MyPoint(1,1),50), c3(MyPoint(2,2),30);
list.Front(&c1);
list.Front(&c2);
list.Front(&c3);
list.Show();
list.Sort();
list.Show();
list.Clean();
list.Show(); /* Recall how Clean method is implemented. As list no longer exist, run-time error is expected here, but flow of executon continues and Show, Push_back preforms fine*/
list.Push_back(&c1);
list.Push_back(&c2);
list.Push_back(&c3);
問題: * 在C語言中的11非標準++聲明析構函數被調用後 - 對象中沒有更長的存在 *,爲什麼我仍然能夠在調用析構函數後使用該對象?
引用一個不再存在的對象是* undefined behavior *。這意味着你的程序可能會崩潰,或者它可能不會。 C/C++不提供安全網絡,並且不需要告訴你是否犯了錯誤。 – DevSolar 2013-02-28 08:51:32
另請參閱:http://stackoverflow.com/a/6445794/78845 – Johnsyweb 2013-02-28 08:54:51
您誤解了它。我認爲真正的意思是*當對象不再存在時,它的析構函數應該被稱爲*。 C++編譯器保證在退出範圍時自動調用每個對象的析構函數。 – neuront 2013-02-28 08:55:46