【问题标题】:scope of objects in cppcpp中对象的范围
【发布时间】:2012-08-31 08:53:15
【问题描述】:

谁能解释一下cpp中创建的对象的范围

#include <iostream>
using namespace std;

class box
{
    public:
        int i;
        box* doubled ();
};

box* box::doubled ()
{
    box *temp = new box;
    temp->i = 2*this->i;
    return temp;
}

int main ()
{
    box *obj1 = new box;
    obj1->i = 5;

    box *obj2;
    obj2 = obj1->doubled();
    delete obj1;
    cout << "i = " << obj2->i << endl;
    return 0;
}

在上面的示例代码中,obj2 是一个指针,它保存由函数 Double 创建的内存。 temp 的范围应该只对 double 的函数有效,但它也可以在 main 函数中访问。

那么任何人都可以解释为什么会发生这种情况。我想这是一个小疑问,但无法弄清楚。

【问题讨论】:

  • 只需评论:this-&gt; 是不必要的。

标签: c++ object scope


【解决方案1】:

你没有删除函数doubled中动态创建的对象,所以指向它的指针当然仍然有效。操作员new 动态分配对象,并且它们保留在内存中直到显式销毁。只有指向内存地址的指针temp 变量)被销毁,但由于您返回了它的值(地址),内存仍然属于程序。实际上不删除会造成内存泄漏。

如果您希望在范围结束后删除您的对象,您应该使用std::unique_ptr

这是一个没有动态分配的简单示例:

T* foo ()
{
    T T_instance;
    return &T_instance;
}

它甚至不应该编译,消息类似于returning address of local variable or temporary,表明程序退出后T_instance将被销毁foo()

【讨论】:

    【解决方案2】:

    当你这样做时:

    box *temp = new box;
    

    您创建了一个动态分配的 box 对象,它存在于所有范围之外,以及一个名为 tempbox* 存在于本地范围中。您必须自己通过在指向它的指针上调用 delete 来释放动态分配的对象,例如,像这样:

    delete temp;
    

    上面代码行中唯一尊重范围的是实际指针temp,它指向该对象。

    {
       box *temp = new box; // local box* points to dynamically allocated object
    }
    // temp is out of scope, but the object it pointed to is still alive (and unreachable)
    

    【讨论】:

      【解决方案3】:

      doubled的返回值是new分配的指针。该指针的值是堆上box 对象的地址,因此虽然temp 是临时的,但它的值存储在这一行的obj2

      obj2 = obj1->doubled(); 
      

      因此当您通过obj2 访问数据时,它仍然有效。

      【讨论】:

        猜你喜欢
        • 2011-04-25
        • 1970-01-01
        • 2013-02-17
        • 1970-01-01
        • 2013-10-21
        • 2016-11-16
        • 2020-12-21
        • 2011-11-03
        • 1970-01-01
        相关资源
        最近更新 更多