我有一个派生自std :: streambuf的类。我不知道为什么或在哪里泄漏,但;根据我正在使用的工具,我的代码中的最后一点看起来是在这个类的某个地方(但它不能提取行号)我的自定义streambuf类中的内存泄漏
这个想法是,该类可以容纳任何数量的streambufs它会将数据同步到。 (例如,std :: cout和ofstream.rdbuf)我将我的数据存储在一个字符串中,直到我得到std :: endl,我在其中写入所有streambuf
任何人都可以指向我可以在哪里泄漏内存?
这是我的头:
#ifndef _MY_STREAM_BUF_H
#define _MY_STREAM_BUF_H
#include <iostream>
#include <algorithm>
#include <list>
#include "../../../Interface/EngineDefs.h"
namespace MyEngine
{
class MyStreamBuf : public std::streambuf
{
public:
MyStreamBuf();
~MyStreamBuf();
void AddStream(std::streambuf* sb);
void RemoveStream(std::streambuf* sb);
bool IsStreamAdded(std::streambuf* sb);
private:
std::list<std::streambuf*> mStreamBufs;
std::string mLine;
int32_t overflow(int32_t c);
int32_t sync();
};
}
#endif
CPP文件:
#include "../../../Include/Core/Logging/MyStreamBuf.h"
namespace MyEngine
{
MyStreamBuf::MyStreamBuf() : std::streambuf()
{
}
MyStreamBuf::~MyStreamBuf()
{
mStreamBufs.clear();
mLine.clear();
}
void MyStreamBuf::AddStream(std::streambuf* sb)
{
if (sb)
mStreamBufs.push_back(sb);
}
void MyStreamBuf::RemoveStream(std::streambuf* sb)
{
if (sb)
mStreamBufs.remove(sb);
}
bool MyStreamBuf::IsStreamAdded(std::streambuf* sb)
{
if (sb)
return (std::find(mStreamBufs.begin(),mStreamBufs.end(),sb) != mStreamBufs.end());
else
return false;
}
int32_t MyStreamBuf::overflow(int32_t c)
{
int32_t r1 = 0, r2 = 0;
if (c == EOF)
return !EOF;
else
{
mLine += c;
return r1 == EOF || r2 == EOF ? EOF : c;
}
}
int32_t MyStreamBuf::sync()
{
int32_t res = 0;
for(std::list<std::streambuf*>::iterator it = mStreamBufs.begin(); it != mStreamBufs.end(); ++it)
{
if (*it)
{
(*it)->sputn(mLine.c_str(),mLine.length());
res &= (*it)->pubsync();
}
}
mLine.clear();
return res == 0 ? 0 : -1;
}
}
是你的streamBuf *动态分配的吗?我看到一个调用remove(),这是否执行删除? – EdChum 2012-04-08 22:22:02
你是指mStreambuf成员还是MyStreamBuf类?添加的streambufs是例如std :: cout.rdbuf或ofstream.rdbuf(我关闭并删除) – KaiserJohaan 2012-04-08 22:34:17
我的意思是任何被传入'无效MyStreamBug :: RemoveStream(std :: streambuf * sb)'是sb动态分配?如果是这样,那么你应该删除它作为删除只是删除条目,而不是做适当的事情,因为你正在存储指针,否则最好有一个容器存储'shared_ptr'而不是原始指针 –
EdChum
2012-04-08 22:36:46