我正在实现一个双向链表类,它存储“桶”(节点),每个都包含预定义数量的字符。每个bucket存储一个指向下一个和前一个bucket的指针,list类(BucketString)存储一个指向head Bucket的指针。我正在使用抛出错误的 g++ 进行编译
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
make: *** [run] Aborted (core dumped)
每当我运行代码并将字符串添加到列表中时,使用以下添加方法,该方法包含在我的存储桶类中,并在需要时从列表类自己的方法中调用。
代码:
std::size_t bucketSizeB;
int filled;
char* str;
Bucket* next;
Bucket* prev;
Bucket::Bucket() : bucketSizeB(7), str(new char[7]), next(NULL), prev(NULL), filled(0)
{}
Bucket::Bucket(std::size_t bucketSizeB_) : bucketSizeB(bucketSizeB_), str(new char[bucketSizeB]), next(NULL), prev (NULL), filled(0)
{}
Bucket::Bucket(const Bucket& rhs) : bucketSizeB(rhs.bucketSizeB), next(rhs.next), prev(rhs.prev), filled(rhs.filled)
{
for (int i = 0 ; i < (int) bucketSizeB ; i++)
{
str[i] = rhs.str[i];
}
}
void Bucket::add(std::string line)
{
int diff = bucketSizeB - filled; //if the bucket is already partially filled
std::string tmp = line.substr(0, diff);
for (std::size_t i = 0 ; i < tmp.length() ; i++)
{
str[filled] = line[i];
++filled;
}
if (line.length() > bucketSizeB)
{
next = new Bucket(bucketSizeB);
next->prev = this;
next->add(line.substr(diff, line.length()-diff));
}
}
Bucket::~Bucket()
{
if (prev)
{
if (next)
{
prev->next = next;
}
else
{
prev->next = NULL;
}
}
if (next)
{
if (prev)
{
next->prev = prev;
}
else
{
next->prev = NULL;
}
}
delete [] Bucket::str;
}
抛出错误时,正在从“list”类成员方法 append 调用 add 方法,其工作原理如下:
void BucketString::append (std::string& line)
{
length += line.length(); //Just a way to store the length of the string stored in this BucketString object
if (!head) //If the head node pointer is currently null, create a new head pointer
{
head = new Bucket(bucketSize);
}
Bucket* tmp = head;
while (tmp->next) //Finds the tail node
{
tmp = tmp->next;
}
tmp->add(line); //Calls the Bucket add function on the tail node
}
桶类的头文件是:
#include <cstddef>
#include <string>
#include <iostream>
#ifndef BUCKET_H_
#define BUCKET_H_
namespace RBNWES001
{
class Bucket
{
public:
//Special members and overloaded constructor
Bucket(void);
Bucket(std::size_t);
Bucket(const Bucket&);
~Bucket();
//Copy Assignment not included because it's not needed, I'm the only one who is gonna use this code! :)
//Add method
void add(std::string);
int filled;
char* str;
Bucket* next;
Bucket* prev;
std::size_t bucketSizeB;
};
}
#endif