#include <list>
#include <iostream>
struct Foo
{
Foo(int a):m_a(a)
{}
~Foo()
{
std::cout << "Foo destructor" << std::endl;
}
int m_a;
};
int main()
{
std::list<Foo> a;
Foo b(10);
std::cout << &b << std::endl;
a.push_back(b);
Foo* c = &(*a.begin());
std::cout << c << std::endl;
a.erase(a.begin());
std::cout << a.size() << std::endl;
c->m_a = 20;
std::cout << c->m_a << std::endl;
std::cout << b.m_a << std::endl;
}
結果是:爲什麼我可以在列表中刪除一個列表中的對象的成員變量?
0x7fff9920ee70
0x1036020
Foo destructor
0
20
10
Foo destructor
我通常認爲i之後擦除在一個列表中我不能訪問塔爾對象的成員變量的任何更多的對象。但是在上面我仍然可以訪問c->m_a
之後,我已經擦除了c
指向的對象,爲什麼?
搜索並閱讀* undefined behavior *。 –
我會想象這是因爲指針仍指向內存,並且知道對象的結構,而真正的析構函數只是允許內存被覆蓋,但這還沒有發生呢 – wrossmck
閱讀[本答案](http ://stackoverflow.com/a/6445794/1782465)。 – Angew