首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从对象自身的虚方法中间接销毁对象。这是一种定义的行为吗?

从对象自身的虚方法中间接销毁对象。这是一种定义的行为吗?
EN

Stack Overflow用户
提问于 2010-08-13 05:51:05
回答 5查看 277关注 0票数 1

允许我从object自己的虚方法中间接销毁object吗?这是一种“定义的行为”吗(只要我在销毁对象后没有试图访问任何东西)?

示例:

代码语言:javascript
复制
#include <memory>
#include <stdio.h>

using std::tr1::shared_ptr;

struct Child{
    virtual void selfdestruct() = 0;
    virtual ~Child(){
        fprintf(stderr, "child destroyed\n");

    }
};

typedef shared_ptr<Child> ChildPtr;

struct Parent{
    ChildPtr child;
    void clear(){
        fprintf(stderr, "clear\n");
        child = ChildPtr();
    }   
    Parent();
};

struct DerivedChild: public Child{
    Parent* parent;

    virtual void selfdestruct(){
        fprintf(stderr, "selfdestruct\n");
        if (parent)
            parent->clear();
    }

    DerivedChild(Parent* p)
    :parent(p){
    }
};

Parent::Parent(){
    child = ChildPtr(new DerivedChild(this));
}


int main(int argc, char** argv){
    Parent p;
    p.child->selfdestruct();    
    fprintf(stderr, "child is 0x%08x\n", p.child);
    return 0;
}

输出:

代码语言:javascript
复制
selfdestruct
clear
child destroyed
child is 0x00000000

如果这不是已定义的行为,我还能做什么呢?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-08-13 05:54:37

虚拟方法可以调用delete this。但是,在调用之后,不能执行任何其他涉及该对象实例的操作,或者您已经调用了未定义的行为。这包括调用其他方法(甚至非虚方法)、访问任何实例变量等。

上面的特定代码调用未定义的行为,因为Child对象需要一个虚拟析构函数。

然而,任何一种对象需要自我销毁的情况都不是最好的设计。

票数 4
EN

Stack Overflow用户

发布于 2010-08-13 05:52:57

对象可以自毁。我看不出作为一个虚拟方法会有什么改变。

票数 1
EN

Stack Overflow用户

发布于 2010-08-13 05:58:39

这基本上归结为一个delete this;,所以答案是肯定的,它是允许的。

代码语言:javascript
复制
void clear(){
    fprintf(stderr, "clear\n");
    child = ChildPtr();
}   
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3472342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档