dimanche 17 mai 2015

Perfect forwarding. Templates

Can someone explain me why my perfect forwarding constructor is infinitely calling ? I got on terminal infinite message " endless " as you can see in code. In real code I'm using my class with some user-defined type.

#include <iostream>
#include <vector>
#include <iostream>
using namespace std;

template<class T>
class test
{
 public:
   ~test(){delete elements; }

  void addItem(T element){
  elements->push_back(element);
  }
  T getItem(int i){
  return elements[i];
  }
  test(){
  elements=new vector<T>;
  }
  test(const test&other){
  elements=new vector<T>;
  elements->assign(other.elements->begin(),other.elements->end() );
  }
  test& operator=( const test&other){
  elements->assign(other.elements->begin(), other.elements->end() );
  }

  /* here I got endless moving ?
     Why ?
  */
  test(test&&other){
  cerr<<"endless";
  elements=other.elements;
  other.elements=nullptr;
  }
  test& operator=(test&& other){
  swap(*this,other);
  return *this;
  }
  test operator+(const test& t2){
  test result(*this);
  auto it2=t2.elements->begin();
  for (auto &v: *elements)
  v=v+*it2;
  return result;
  }
  vector<T>* elements;
};

int main()
{

test<int> t1,t2,t3;
t3=t1+t2;

return 0;
}

Aucun commentaire:

Enregistrer un commentaire