lundi 27 février 2017

How to take advantage of the Move Semantics for a better performance in C++11?

After many trials I still do not understand how to properly take advantage of the move semantics in order to not copy the result of the operation and just use the pointer, or std::move, to "exchange" the data pointed to. This will be very usefull to speed-up more complicated functions like f(g(),h(i(l,m),n(),p(q())) The objective is to have:

t3={2,4,6}; 
t1={}; // empty

While executing the code below the output is:

t3={2,4,6};
t1={1,2,3};

Code:

namespace MTensor {

 typedef std::vector<double> Tensor1DType;

 class Tensor1D {
  private:
    //std::shared_ptr<Tensor1DType> data = std::make_shared<Tensor1DType>();
    Tensor1DType * data = new Tensor1DType;
  public:
    Tensor1D() {
  };
  Tensor1D(const Tensor1D& other) {
    for(int i=0;i<other.data->size();i++) {
      data->push_back(other.data->at(i));
    }
  }
  Tensor1D(Tensor1D&& other) : data(std::move(other.data)) {
    other.data = nullptr;
  }
  ~Tensor1D() {
    delete data;
  };
  int size() {
    return data->size();
  };
  void insert(double value) {
    data->push_back(value);
  }
  void insert(const std::initializer_list<double>&  valuesList) {
    for(auto value : valuesList) {
      data->push_back(value);
    }
  }
  double operator() (int i) {
    if(i>data->size()) {
      std::cout << "index must be within vector dimension" << std::endl;
      exit(1);
    }
    return data->at(i);
  }
  Tensor1D& operator=(Tensor1D&& other)  {
    if (this == &other){
      return *this;
    }
    data = other.data;
    other.data = nullptr;
    return *this;
  }
  void printTensor(Tensor1DType info) {
    for(int i=0;i<info.size();i++) {
      std::cout << info.at(i) << "," << std::endl;
    }
  }
  void printTensor() {
    for(int i=0;i<data->size();i++) {
      std::cout << data->at(i) << "," << std::endl;
    }
  }
};
} // end of namespace MTensor

Aucun commentaire:

Enregistrer un commentaire