class B
{
public:
B():a(0), b(0) { }
B(int x):a(x), b(0) { }
private:
int a;
int b;
};
class A
{
public:
A(B* ptr):pB(ptr) { }
void modifypB()
{
delete pB;
pB = NULL;
}
void printBSize()
{
if( pB != NULL )
cout<<"pB pointing to Obj size:"<<sizeof(*pB)<<endl;
else
cout<<"pB pointing to Obj size:"<<sizeof(*pB)<<endl;
}
private:
B *pB;
};
void main()
{
B *bObj = new B(10);
cout<<"Size of bObj:"<<sizeof(*bObj)<<endl;
A aObj(bObj);
cout<<"Size of aObj:"<<sizeof(aObj)<<endl;
cout<<"Before De-allocating: ";
aObj.printBSize();
aObj.modifypB();
cout<<"After De-allocating: ";
aObj.printBSize();
}
输出:
Size of bObj: 8
Size of aObj: 4
Before De-allocating: pB pointing to Obj size: 8
After De-allocating: pB pointing to Obj size: 8
为什么*pB
即使在取消分配之后,大小也是 8?