参考自: https://blog.csdn.net/RUN32875094/article/details/78462718
一般的函数返回的对象是个临时对象, 在返回赋值语句完成后就会析构; 部分情况不会产生临时对象
1 #include <iostream> 2 class aaa 3 { 4 public: 5 aaa(int a1) 6 :a(a1) 7 { 8 printf("gouzao %d %x ", a,this); 9 } 10 aaa() 11 :a(0) 12 { 13 printf("gouzao1 %d %x ", a, this); 14 } 15 aaa(const aaa &a1) 16 :a(a1.a) 17 { 18 printf("gouzao2 %d %x ", a, this); 19 } 20 ~aaa() 21 { 22 printf("xigou %d %x ", a, this); 23 } 24 public: 25 void print() 26 { 27 printf("aaaaa "); 28 } 29 operator char*() 30 { 31 printf("adsfd "); 32 return NULL; 33 } 34 35 int a = 0; 36 }; 37 38 aaa GetObject() 39 { 40 aaa aa(10); 41 aa.a = 9; 42 return aa; 43 } 44 int wmain(int argc, wchar_t **argv) 45 { 46 printf("main start "); 47 GetObject().print();// 返回临时对象,该语句结束后, 返回临时对象就会析构 48 char *aa = GetObject();// 返回临时对象,这句话之后, 返回临时对象就会析构, 之后aa就会成为也指针 49 aaa a1 = GetObject();// 不返回临时对象, GetObject()内部的aa对象作为参数传给a1的拷贝构造函数 50 printf("main end "); 51 system("pause"); 52 return 0; 53 }