【问题标题】:What happens to an object of a class in a function函数中类的对象会发生什么
【发布时间】:2015-03-02 00:40:11
【问题描述】:

如果我创建一个类,并将它的对象放在一个函数中*。一旦函数结束,我创建的对象会发生什么?它会被删除吗?

编辑: *我从主函数调用该函数

【问题讨论】:

    标签: c++ function class object


    【解决方案1】:

    当您在代码块中声明变量时,该变量的生命周期会一直持续到代码块的末尾。变量将在其生命周期结束时被销毁,也就是控制退出该块时。

    这个的正确名称是自动存储持续时间,尽管有时会使用“在堆栈上”的行话。

    如果您想保留变量中的值,则可以返回变量的副本(不用担心,编译器通常会对此进行优化)。

    还可以创建具有手动管理生命周期的对象。在这种情况下,对象没有名称,您可以通过句柄管理它们,直到您在它们的句柄上调用 delete,它们的生命才会结束。

    这种技术需要更加小心,并且比使用自动变量更复杂;更喜欢使用自动变量,除非你真的无法用它们解决问题。

    【讨论】:

    • 确实如此。我基本上是在寻找一种方法,使对象在结束功能时被删除。我认为最好的方法是从函数中调用它,但我不确定这是否可行,呵呵。现在我是:)
    【解决方案2】:

    “它会被删除吗?”

    是的。只要您使用自动存储持续时间(有时称为堆栈分配)创建了该对象实例,它就会在超出范围时立即被删除。

    struct Foo {
        Foo() {}
        ~Foo() {}
    };
    
    void bar() {
        Foo foo1; // automatic storage duration
        Foo* foo2 = new Foo(); // manually-managed lifetime
    } // foo1 will be deleted here, while foo2 won't
    

    【讨论】:

    • “在堆栈上”是什么意思?抱歉,我还是 C++ 新手 :)
    • @shadoweye14 我已经给出了更多解释
    • @LightnessRacesinOrbit 更好?
    【解决方案3】:

    它将作为本地范围的任何其他变量被删除。当您创建其中之一时,它们将一直存在到函数结束,除非您创建指针。在这种情况下,函数结束后数据仍然存在,但您可能会丢失引用。

    class myClass{
    int variable;
    float etc;
    }
    
    void foo()
    {
    myClass foo1 = new myClass(); // creates new instance of myClass
    // as it was declared inside the function it only local scope
    myClass* foo2; // it is a pointer
    *foo2 = foo1; // foo2 won't be deleted. The data will still be there
    // However, if you loose the reference to it,
    // you may not be able to access the data stored
    
    }
    
    int main()
    {
    // foo1 still does not exist
    foo(); // foo1 is created and deleted inside foo()
    // main still can't "see" foo1 because of its scope
    // foo2 still exists - the memory has been alocated and has a copy of  
    // foo1 in it, but main can't access it because it does not have the
    // reference to the memory address.
    }
    

    请注意,如果您在用于创建对象的函数中使用另一个函数,它也将无法访问它。

    【讨论】:

    • myClass foo1 行无法编译,*foo2 = foo1; 取消引用未初始化的指针
    • 你在类定义之后缺少;。请在教别人之前测试你的代码!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多