c++中返回对象的内存分配

Memory allocation of returned object in c++

从以下代码的最后一行返回的对象发生了什么

class weight
{
   int kilogram;
   int gram;
public:
   void getdata ();
   void putdata ();
   void sum_weight (weight,weight) ;
   weight sum_weight (weight) ;
};
weight weight :: sum_weight(weight w2)
{
   weight temp;
   temp.gram = gram + w2.gram;
   temp.kilogram=temp.gram/1000;
   temp.gram=temp.gram%1000;
   temp.kilogram+=kilogram+w2.kilogram;
   return(temp);
}
int main(){
//.....//
   w3=w2.sum_weight(w1);
   w2.sum_weight(w1);
//.....//
}

它是保留在内存中直到完成还是被删除。

sum_weight(w1); 将 return 一个对象,但你没有分配它意味着对象从未使用过。在第一种情况下 w3=w2.sum_weight(w1); 它将调用赋值运算符以及复制构造函数和默认构造函数(即 temp) .在第二种情况下,将创建 weight 的两个实例(第一个 (weight w2) 和第二个 weight temp;)。 Hance 在退出主方法之前 O/S 将调用两个对象的析构函数。 W3 和从语句 w2.sum_weight(w1);(即 temp

创建的临时对象

让我们看看到底发生了什么:

#include <stdio.h>

class A {
    public:
        A() { printf("default constructing at %016zx\n", (size_t)this); }
        A(const A& a) { printf("copy constructing from %016zx at %016zx\n", (size_t)&a, (size_t)this); }
        void operator=(const A& a) { printf("assigning from %016zx to %016zx\n", (size_t)&a, (size_t)this); }
        ~A() { printf("destructing at %016zx\n", (size_t)this); }
        static A makeA() {
            A temp;
            return temp;
        }
};

int main() {
    A a;
    printf("calling makeA()\n");
    a = A::makeA();
    printf("returned from makeA()\n");
}

此代码在我的机器上产生以下输出(没有编译器优化!):

default constructing at 00007ffe39415d0e
calling makeA()
default constructing at 00007ffe39415d0f
assigning from 00007ffe39415d0f to 00007ffe39415d0e
destructing at 00007ffe39415d0f
returned from makeA()
destructing at 00007ffe39415d0e

所以,你看,在调用过程中,makeA()中的变量被创建,makeA()中变量的值被赋值给main()中的变量,并且变量在 makeA() 中被销毁。 main() 中的变量是在调用之前创建的,并且在 main() returns 到它的调用者之前一直有效。