Changeset 4010


Ignore:
Timestamp:
Oct 19, 2020, 4:33:47 AM (11 months ago)
Author:
Peter
Message:

Implement move constructo and move-assignment operator for
DiscreteGeneral? (closes #964). Using swap idiom also for
copy-assignment as it gives stronger exception safety, i.e., if
preproc throws, lhs is not modified (whereas before ::p_ was).

Location:
trunk/yat/random
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/yat/random/random.cc

    r4009 r4010  
    241241
    242242
     243  DiscreteGeneral::DiscreteGeneral(DiscreteGeneral&& other)
     244    : Discrete(std::move(other)), gen_(nullptr), p_(std::move(other.p_))
     245  {
     246    gen_ = std::move(other.gen_);
     247  }
     248
     249
    243250  DiscreteGeneral::~DiscreteGeneral(void)
    244251  {
     
    267274  DiscreteGeneral& DiscreteGeneral::operator=(const DiscreteGeneral& rhs)
    268275  {
    269     free();
    270     p_ = rhs.p_;
    271     preproc();
     276    DiscreteGeneral tmp(rhs);
     277    swap(*this, tmp);
    272278    return *this;
    273279  }
    274280
    275281
     282  DiscreteGeneral& DiscreteGeneral::operator=(DiscreteGeneral&& rhs)
     283  {
     284    DiscreteGeneral tmp(std::move(rhs));
     285    swap(*this, tmp);
     286    return *this;
     287  }
     288
     289
    276290  unsigned long DiscreteGeneral::operator()(void) const
    277291  {
    278292    return gsl_ran_discrete(rng_->rng(), gen_);
     293  }
     294
     295
     296  void swap(DiscreteGeneral& lhs, DiscreteGeneral& rhs)
     297  {
     298    std::swap(lhs.gen_, rhs.gen_);
     299    std::swap(lhs.p_, rhs.p_);
    279300  }
    280301
  • trunk/yat/random/random.h

    r4009 r4010  
    363363    DiscreteGeneral(const DiscreteGeneral&);
    364364
     365    /**
     366       \brief Move constructor
     367
     368       \since New in yat 0.19
     369     */
     370    DiscreteGeneral(DiscreteGeneral&&);
     371
    365372    ///
    366373    /// @brief Destructor
     
    385392    DiscreteGeneral& operator=(const DiscreteGeneral&);
    386393
     394    /**
     395       \brief Move assignment operator
     396
     397       \since New in yat 0.19
     398     */
     399    DiscreteGeneral& operator=(DiscreteGeneral&&);
     400
    387401  private:
    388402    void free(void);
     
    391405    gsl_ran_discrete_t* gen_;
    392406    std::vector<double> p_;
    393   };
     407    friend void swap(DiscreteGeneral& lhs, DiscreteGeneral& rhs);
     408  };
     409
     410  /**
     411     \relates DiscreteGeneral
     412
     413     \since Specialisation new in yat 0.19
     414   */
     415  void swap(DiscreteGeneral& lhs, DiscreteGeneral& rhs);
    394416
    395417  /**
Note: See TracChangeset for help on using the changeset viewer.