注册 登录
编程论坛 C++教室

太奇怪了 对象被删除 却不调用析构函数

ml232528 发布于 2008-09-25 20:01, 1238 次点击
用a类的静态成员函数Createit 创建几个b类连续的内存空间 再用Freeit删除它 去不调用b类析构函数
源代码如下:



#include <stdio.h>
#include <tchar.h>
#include<windows.h>


class a
{
public:
    a *data(){return this+1;}
    static a* Createit(a*& head,UINT m,UINT n);
    void Freeit();    
};

a *a::Createit(a*& head, UINT m, UINT n)
{
    head=(a*)new BYTE[sizeof(a)+m*n];
    return head;
}

void a::Freeit()
{
    a* p=this;
    BYTE *p1=(BYTE*)p;
    delete[] p1;    
}





class b
{
public:
    int x;
    ~b(){printf("对象被删除\n");}               //至始至终没调用它
};



int _tmain(int argc, _TCHAR* argv[])
{    
    a* p=a::Createit(p,5,sizeof(b));
    b *b1=(b*)p->data();
    b *b2=b1+1;
    b1->x=5;b2->x=6;
    printf("b1->x=%d,b2->x=%d\n",b1->x,b2->x);
    p->Freeit();                                 //删除对象
    printf("b1->x=%d,b2->x=%d\n",b1->x,b2->x);
    getchar();    
    return 0;
}
8 回复
#2
出海之渔人2008-09-25 22:31
有点晕
#3
sunkaidong2008-09-26 14:04
#include <stdio.h>
#include <tchar.h>
#include<windows.h>
class b
{
public:
    int x;
    b(){};
    ~b(){printf("对象被删除\n");}               //至始至终没调用它
};

class a
{
public:
    a *data(){return this+1;}
    static a* Createit(a*& head,UINT m,UINT n);
    void Freeit();   
};

a *a::Createit(a*& head, UINT m, UINT n)
{
    head=(a*)new BYTE[sizeof(a)+m*n];
    return head;
}

void a::Freeit()
{
    //a* p=this;
    b *p1=new b();
    delete p1;   
}









int _tmain(int argc, _TCHAR* argv[])
{   
    a* p=a::Createit(p,5,sizeof(b));
    b *b1=(b*)p->data();
    b *b2=b1+1;
    b1->x=5;b2->x=6;
    printf("b1->x=%d,b2->x=%d\n",b1->x,b2->x);
    p->Freeit();                                 //删除对象
    printf("b1->x=%d,b2->x=%d\n",b1->x,b2->x);
    getchar();   
    return 0;
}
#4
ml2325282008-09-27 09:56
楼上你的方法根本没有删除b1和b2,因为x的值没变 。

运行楼主的程序可以看到, x的值很奇怪,说明b1和b2已被删除了
#5
sunkaidong2008-09-27 10:38
~b(){printf("对象被删除\n");}               //至始至终没调用它
我是为了证明调用这个代码。。。
#6
BlueMouse2008-09-27 11:07
这样写代码的还真少见呀!不过这代码我怎么看你都没有使用到 class b 的对象和指针呀?

自然不会调用class b的析构函数了?难道我看不出来!
#7
ml2325282008-09-27 12:54
可能是强制转换的问题
强制类型转换就会出现 析构函数被调用或不被调用的情况 如下



#include<iostream>
using namespace std;


class a
{
public:
    int x;
    a(){cout<<"对象被创建"<<endl;}
    ~a(){cout<<"对象被删除"<<endl;}
};

int main()
{
    unsigned char *b1=new unsigned char[sizeof(a)];
    delete (a*)b1;                  //调用了析构函数 但b1不是a类
    a* a1=new a;
    delete (int*)a1;                //不调用析构函数 虽然a1是a类
    getchar();   
    return 0;
}

[[it] 本帖最后由 ml232528 于 2008-9-27 12:56 编辑 [/it]]
#8
BlueMouse2008-09-27 13:34
晕!当然了!这样肯定是不会调用的!
#9
hbhbhb20082008-11-12 19:17
我要删除自己的帖子 怎么没人发关于删帖子的主题呢
1