それぞれが定義済みの文字数を含む「バケット」(ノード) を格納する種類の二重リンク リスト クラスを実装しています。各バケットには前後のバケットへのポインタが格納され、リスト クラス (BucketString) には先頭のバケットへのポインタが格納されます。エラーをスローする g++ を使用してコンパイルしています
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
make: *** [run] Aborted (core dumped)
コードを実行し、リストに文字列を追加するたびに、次の add メソッドを使用します。このメソッドはバケット クラスに含まれており、必要に応じてリスト クラスの独自のメソッドから呼び出されます。
コード:
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;
}
エラーがスローされると、「リスト」クラス メンバー メソッド 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