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