免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6874 | 回复: 8
打印 上一主题 下一主题

[C++] 如何避免析构函数调用两次 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-11-05 11:48 |只看该作者 |倒序浏览
mathgl.h
  1. #include <mgl/mgl_c.h>

  2. class mglGraph {
  3.     HMGL gr;
  4. public:
  5.     mglGraph(int kind, int width, int height);
  6.     ~mglGraph();
  7. };
复制代码
mathgl.cpp
  1. #include "mathgl.h"
  2. #include <iostream>

  3. using namespace std;

  4. mglGraph::mglGraph(int kind, int width, int height) {
  5.     std::cout << "new" << std::endl;
  6.     if (kind == 0)
  7.         gr = mgl_create_graph_zb(width, height);
  8.     else if (kind == 1)
  9.         gr = mgl_create_graph_ps(width, height);
  10. }

  11. mglGraph::~mglGraph() {
  12.     std::cout << "delete" << std::endl;
  13.     mgl_delete_graph(gr);
  14. }
复制代码
exam.cpp
  1. #include <iostream>
  2. #include "mathgl.h"

  3. using namespace std;

  4. int main() {
  5.     mglGraph w(1,1,1);
  6.     return 0;
  7. }
复制代码
运行输出如下:
new
delete
delete
Segmentation fault
为什么析构函数调用了两次,如何让它只调用一次?谢谢!

论坛徽章:
0
2 [报告]
发表于 2011-11-16 11:21 |只看该作者
回复 1# zhengyj


    这点儿代码,谁能看出来?

论坛徽章:
0
3 [报告]
发表于 2011-11-16 11:26 |只看该作者
好像OIOIC能自动避免构造函数和析构函数被调用两次,保证只调用一次。不是为OIOIC做广告呀。。。。

论坛徽章:
0
4 [报告]
发表于 2011-11-16 11:55 |只看该作者
无代码无真相。。。。

在构造和析构函数加个断点,看看什么时候进到这两个地方来罗

胡乱猜一下,某个地方调用了一个拷贝构造函数(默认生成),所以多一个析构。

论坛徽章:
0
5 [报告]
发表于 2011-11-16 11:57 |只看该作者
谁知道你mgl_delete_graph函数是怎么实现的。

论坛徽章:
0
6 [报告]
发表于 2011-11-16 12:59 |只看该作者
有代码没贴出来,从现有的看不出来,正常应当是不会有两次的。由于第一次delete,gr已经变成无效内存了,第二次delete就coredump了。

论坛徽章:
0
7 [报告]
发表于 2011-11-16 13:06 |只看该作者
智能指针?

论坛徽章:
0
8 [报告]
发表于 2011-11-17 09:23 |只看该作者
回复 1# zhengyj


    你将mathgl.cpp的第16行mgl_delete_graph(gr);注释掉,再编译运行一下,不就知道了到底是哪里出了错误了。

论坛徽章:
0
9 [报告]
发表于 2011-11-17 13:27 |只看该作者
调试一下
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP