首页
社区
课程
招聘
[旧帖] [原创]STL代码报错,求解释! 0.00雪花
发表于: 2013-11-20 14:03 2192

[旧帖] [原创]STL代码报错,求解释! 0.00雪花

2013-11-20 14:03
2192
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template<class type>
class Print
{
        char *mpBuffer;
public:
        Print()
        {
                mpBuffer = new char;
                cout<<"Start:"<<endl;
        }
        ~Print()
        {
                delete mpBuffer;
                cout<<"End"<<endl;
        }
        void operator()(const type& Elem)
        {
                cout<<Elem<<endl;
        }
};
int _tmain(int argc, _TCHAR* argv[])
{
        int ia[6] = {0, 1, 2, 3, 4, 5};
        vector<int> iv(ia, ia+5);
        //Print<int>();

        for_each(iv.begin(), iv.end(), Print<int>());

        return 0;
}

其中,初始化了一次Print<int>对象,但是却析构了三次。在第二次delete内存的时候报错,求解释!为什么会析构三次?难道是STL库的Bug?

[培训]《安卓高级研修班(网课)》月薪三万计划,掌握调试、分析还原ollvm、vmp的方法,定制art虚拟机自动化脱壳的方法

收藏
免费 0
支持
分享
最新回复 (7)
雪    币: 144
活跃值: (46)
能力值: ( LV6,RANK:90 )
在线值:
发帖
回帖
粉丝
2
用c++11  高端啊,,。。。有的什么编译器?
2013-11-20 14:08
0
雪    币: 4
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
3
vs2008
2013-11-20 14:22
0
雪    币: 7
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
4
C++11好用吗?g++ 是 C++11么。MINGW  和 CodeBlocke 配合好用么。一直用VC6.0 独立编程。
2013-11-25 23:33
0
雪    币: 220
活跃值: (25)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
5
stl没有错,因为for_each返回函数对象的一个拷贝,是你函数对象搞错了,没有写拷贝构造函数,编译器添加了一个默认拷贝构造函数,直接把指针赋值了,那样会对同一个地址删除两次,结果可想而知了,呵呵~~应该把拷贝构造函数写好,就没有问题了。
template<class type>
class Print
{
        char *mpBuffer;
public:
        Print()
        {
                mpBuffer = new char;
                cout<<"Start:"<<endl;
        }
        Print(const Print<type>& p) //拷贝构造函数
        {
                mpBuffer = new char;
                *mpBuffer = *(p.mpBuffer);
        }
        ~Print()
        {
                delete mpBuffer;
                mpBuffer = NULL;
                cout<<"End"<<endl;
        }
        void operator()(const type& Elem)
        {
                cout<<Elem<<endl;
        }
};
2013-11-26 09:50
0
雪    币: 4
活跃值: (10)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
6
你怎么找到是拷贝函数除了问题呢?我也跟踪过,但没向导到这种原因
2013-12-9 13:37
0
雪    币: 272
活跃值: (16)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
7
delete出错,你首先就应该检查构造函数这一块。
2013-12-9 14:01
0
雪    币: 220
活跃值: (25)
能力值: ( LV2,RANK:10 )
在线值:
发帖
回帖
粉丝
8
你怎么找到是拷贝函数除了问题呢?我也跟踪过,但没向导到这种原因

查帮助文档MSDN,for_each返回函数对象的一个拷贝。在析构函数~Print()下断点,发现两次delete mpBuffer的地址同一个地址,故查出问题。
2013-12-11 09:20
0
游客
登录 | 注册 方可回帖
返回
//