ダブルリンクリストのコピーコンストラクタ、デストラクタ、および代入演算子を取得しようとすると、多くの問題が発生しています。 私はクラスdlistとノードクラスを持っています。 Nodeクラスには、次および前のプライベートノードとデータフィールドが含まれます。私は本当に立ち往生しているし、私の人生はこれらを稼働させる方法を理解できない。誰かが何が間違っているかを指摘しても。時には私はsegの欠陥を取得し、私は大きな3つの変化に応じて、私はバックトレースを得る他の回。二重リンクリストBig Three
//Destructor
template<class T>
dlist<T>::~dlist(){
node<T> *rmptr = head;
while(head != NULL && head != tail){
head = head -> next();
delete rmptr;
}
}
//Copy Constructor
template <class T>
dlist<T>::dlist(const dlist<T>& other)
{
if(other.head == NULL){
head = new node<T>;
tail -> set_next(head);
}
else{
head = new node<T>(other.head -> data());
tail = new node<T>;
head -> set_next(tail);
tail -> set_previous(head);
node<T> *source = other.head -> next();
node<T> *destination = head;
while(source != NULL && source != other.tail){
tail -> set_next(new node<T>);
destination -> set_next(tail);
tail -> set_data(source -> data());
tail = tail -> next();
source = source -> next();
}
}
}
//Assignment Operator
template<class T>
dlist<T>& dlist<T>::operator =(const dlist& other){
if(this == &other){
return *this;
}
node<T> * rmptr;
while(head != NULL){
rmptr = head;
head = head -> next();
delete rmptr;
}
head = tail = NULL;
node<T> *source, *destination;
if(other.head != NULL){
head = new node<T>(other.head -> data());
tail = new node<T>;
head -> set_next(tail);
tail -> set_previous(head);
node<T> *source = other.head -> next();
node<T> *destination = head;
while(source != NULL && source != other.tail){
tail -> set_next(new node<T>);
destination -> set_next(tail);
tail -> set_data(source -> data());
tail = tail -> next();
source = source -> next();
}
}
return *this;
}
正直なところ、コピーセマンティクスに到達する前でもこのコードにはいくつか問題があります。例:デストラクタは同じポインタ*( 'rmptr'、リストヘッドとして初期化されます)を繰り返し削除し、リストに割り当てられた残りのメモリをリークします(あなたがクラッシュしなかったと想定します)。 – WhozCraig
へのご連絡ありがとうございます。それも参考になりました。 –