我有一个关于为什么我可以访问某些内存块的问题,我认为它与我理解(或不理解)编译器如何将内存保存在内存中的方式有关。这是示例代码我的工作:C++清除的内存仍可访问
头文件:
#include <iostream>
using namespace std;
class A
{
public:
int value;
A (int newValue = 5)
{
value = newValue;
cout << "A()" << endl;
}
~A() { cout <<"~A()" << endl; }
void func1() {cout << "A::func1()" << endl; }
};
class B : public A
{
public:
B() { A::value = 0; cout << "B()" << endl; }
~B() { cout << "~B()" << endl; }
virtual void func1() { cout << "B::func1()" << endl; }
};
class C : public B
{
public:
C() { cout << "C()" << endl; }
~C() { cout << "~C()" << endl; }
virtual void func1() { cout << "C::func1()" << endl; }
};
.cpp文件:
int main()
{
int i;
cout << endl;
A* pA = new A (5);
B* pB = new B;
C* pC = new C;
pA->func1();
pB->func1();
pC->func1();
delete pA;
delete pB;
delete pC;
cout << endl;
//here is my first question - why don't I get a compiler error here?
//why does the compiler know what this is? Didn't I delete it?
A* ppA = pC;
//here is my second question - why does this work?
//didn't I clear this memory?
ppA->func1();
B bObject;
B* ppB = &bObject;
ppB->func1();
cin >> i;
return 0;
}
我的问题是正确的,在评论 - 为什么我没有得到这些线路上的错误?
如果我更改.h文件,使func1()
为virtual
也在A
中,我确实在该行上发生访问冲突,但仍然没有编译时错误。
感谢您的任何解释:)
我相信这可能是因为你用delete删除了内存,但它可能没有写完。因此数据可能仍然存在。但是不确定。 –
仅供参考_compiler_不会将内容保存在内存中。该任务由操作系统执行。 – ALOToverflow
@Francis,啊,那些善良的迂腐人物,他们只是对他们迂腐的东西有一个模糊的概念。你知道G ++在编译一个文件的内存中“保存”了更多的东西,而不是所有的程序放在一起吗?只是“供参考”。 – Blindy