在g ++中删除这个指针行为 [英] delete this pointer behaviour in g++

查看:169
本文介绍了在g ++中删除这个指针行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

class Foo {

        public:
                Foo(char x);
                Foo(char x, int y);
                ~Foo();
                void abc();
                void dev();
};

void Foo::dev()
{

        printf("inside dev \n");
}

void Foo::abc()
{

        printf("inside abc \n");
        delete this;
        dev();
}

Foo::Foo(char x)
{

      printf("inside 1 argu const---------------");

}

Foo::~Foo()
{

    printf("inside 1 argu dest---------------");
}

#include "test.h"

int main()
{

        Foo *obj=new Foo('a');
        printf("%u inside main\n", obj);
        obj->abc();
        return 0;
}



查看程序的输出后,看起来dev仍然被调用,尽管是删除这在函数abc中调用之前调用dev? gcc / g ++如何处理这个问题?

After looking at the output of the program, it seems that "dev" function is still invoked despite being "delete this" is called in function abc before invoking dev ? How does gcc/g++ handles this ?

推荐答案

对象可能仍然可用于未定义的时间。此外, delete 不会影响相关的指针。

The object might be still available for undefined time. Also, delete doesn't affect the pointer in question.

删除只是调用对象实例的析构函数。 删除将内存返回到池,但它是未定义的(和运行时相关),当这个内存将被重用(如果有的话)。对象可以很好地在程序的剩余时间可用,但要点是:不要指望它

Delete just calls the destructor on the object instance. Delete returns the memory to the pool but it is undefined (and runtime related) as to when this memory will be reused (if at all). The object can very well be available for the rest of the duration of the program but the point is: don't count on it.

有一个没有明显的缺陷需要注意:对象无法知道是否动态分配。因此,如果对象静态分配调用,则删除该对象上的将证明有问题。这不是上面的情况。

There is a not so obvious pitfall to take notice of: the object has no way of knowing if it was allocated dynamically. Hence, if the object was statically allocated calling, delete this on the said object will prove problematic. This isn't the case above though.

这篇关于在g ++中删除这个指针行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆