C++ cpp中对象的范围

C++ cpp中对象的范围,c++,object,scope,C++,Object,Scope,有人能解释一下在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 () {

有人能解释一下在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是一个指针,用于保存函数创建的内存。temp的作用域应该只对函数有效,但在主函数中也可以访问它

那么,有谁能解释为什么会发生这种情况呢。我想这是一个小小的疑问,但我无法理解。

当你这样做时:

box *temp = new box;
您可以创建一个动态分配的box对象,该对象位于所有范围之外,以及一个名为temp的box*对象,该对象位于本地范围内。您必须自己通过在指向动态分配对象的指针上调用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)

您没有删除在函数Double中动态创建的对象,因此指向它的指针当然仍然有效。操作符new动态地分配对象,并且在显式销毁之前,它们一直保留在内存中。只有指向temp变量的内存地址的指针被破坏,但由于您将其值返回到了地址,内存仍然属于程序。实际上,不删除它会造成内存泄漏

如果希望在作用域结束后删除对象,则应使用std::unique_ptr

下面是一个没有动态分配的快速示例:

它甚至不应该编译,其消息类似于局部变量或临时变量的返回地址,指示t_实例将在程序退出foo后被销毁。

double的返回值是new分配的指针。该指针的值是堆上一个box对象的地址,因此尽管temp是临时的,但它的值存储在此行的obj2中

obj2 = obj1->doubled(); 
因此,当您通过obj2访问数据时,它仍然有效。

并且只需一条注释:这->是不必要的。
obj2 = obj1->doubled();