lundi 19 avril 2021

C++ overloaded operator= does not work properly

I'm developing a custom Queue List class in C++.
In my main I have:

  QueueLst<int> q1;
  q1.Enqueue(1);
  q1.Enqueue(2);
  q1.Enqueue(3);
  cout<<q1.HeadAndDequeue()<<" "<<q1.HeadAndDequeue()<<" "<<q1.HeadAndDequeue();

that works fine, result:

1 2 3

Now if I write;

  QueueLst<int> q1;
  q1.Enqueue(1);
  q1.Enqueue(2);
  q1.Enqueue(3);
  QueueLst<int> q2;
  q2 = q1;
  cout<<q2.HeadAndDequeue()<<" "<<q2.HeadAndDequeue()<<" "<<q2.HeadAndDequeue();

output:

1
terminate called after throwing an instance of 'std::length_error'
  what():  List is empty!

And this is my operator= method:

template <typename Data>
QueueLst<Data>& QueueLst<Data>::operator=(const QueueLst& toCopy){
   QueueLst<Data>* tmp = new QueueLst<Data>(toCopy);
   std::swap(*this, *tmp);
   delete tmp;
   return *this;
}

And I'm 100% sure the copy consructor works fine, in fact, if I write

template <typename Data>
QueueLst<Data>& QueueLst<Data>::operator=(const QueueLst& toCopy){
   QueueLst<Data>* tmp = new QueueLst<Data>(toCopy);
   return *tmp;
}

It works fine! So there is something strange in the std::swap but how? I'm sorry that this is a very specific question but can't figure out how to fix that, thank you

Aucun commentaire:

Enregistrer un commentaire