鱼C论坛

 找回密码
 立即注册
查看: 3150|回复: 4

关于C++类的析构函数问题

[复制链接]
发表于 2016-4-27 16:32:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
三个文件Point.h、Point.cpp和main.cpp

Point.h文件内容:
  1. #ifndef _POINT_
  2. #define _POINT_

  3. class Point{
  4.        
  5. public:
  6.         int x;
  7.         int y;
  8.        
  9. public:
  10.         Point(int _x=0, int _y=0);
  11.         ~Point();
  12. };

  13. #endif // _POINT_
复制代码


Point.cpp文件内容:
  1. #include "Point.h"

  2. #include <iostream>

  3. using namespace std;

  4. Point::Point(int _x, int _y){
  5.         this->x = _x;
  6.         this->y = _y;
  7.         cout << this << " construction..." << endl;
  8. }

  9. Point::~Point(){
  10.         cout << this << " destruction..." << endl;
  11. }
复制代码


main.cpp文件内容:
  1. #include "Point.h"

  2. #include <iostream>

  3. using namespace std;

  4. Point setPosition(int x, int y){
  5.         Point p(x, y);
  6.         cout << "the address of point is " << &p << endl;
  7.         return p;
  8. }


  9. int main(int argc, char* argv[]){
  10.        
  11.         Point p;
  12.         cout << "the address of point is " << &p << endl;
  13.        
  14.         p = setPosition(2, 4);
  15.         cout << "the address of point is " << &p << endl;
  16.                
  17.         return 0;
  18.        
  19. }
复制代码


用vs2015的cl.exe编译链接器编译运行,结果如下:
0018FEBC construction...
the address of point is 0018FEBC
0018FE84 construction...
the address of point is 0018FE84
0018FE84 destruction...
0018FEB4 destruction...
the address of point is 0018FEBC
0018FEBC destruction...

其中0018FEB4 destruction...这一句没看懂,有没有大牛解释下,谢谢啦~

按照常规思维,构造和析构应该成对出现,地址为0018FE84的这个类应该是函数setPosition里的局部类对象的地址,函数执行完退出时执行析构函数,输出0018FE84 destruction...,这个可以理解,但是0018FEB4 destruction...这句说明还有一个类对象被析构了?,但是它在哪里构造的呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-4-27 17:59:20 | 显示全部楼层
这应该是Point  setPosition(int x, int y)这个函数的地址吧。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-4-27 18:45:30 | 显示全部楼层
我叫淳子 发表于 2016-4-27 17:59
这应该是Point  setPosition(int x, int y)这个函数的地址吧。

不是函数地址
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2016-4-28 09:37:17 | 显示全部楼层
因为函数setPoint结束时函数内部创建的对象要消亡,由于函数要返回一个对象所以在set函数内部临时对象销毁前以它为参数调用复制构造函数(如果没有定义自动调用系统隐含的复制构造函数)再创建一个临时对象返回。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2016-4-28 15:21:24 | 显示全部楼层
LeoChou 发表于 2016-4-28 09:37
因为函数setPoint结束时函数内部创建的对象要消亡,由于函数要返回一个对象所以在set函数内部临时对象销毁 ...

Thanks!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 08:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表