C++ vectors, sorting and custom class operators -


i puzzled because cannot figure bug/problem is. have class instruction, uses 2 custom operators, 1 assignment , 1 comparison operator. used comparison operator in order use std::sort sort instructions based on 1 of members, std::string name. however, since started re-factoring entire project, changed members constant. lead me having use initialization list constants. in turn, lead me have create assignment operator, because instructions being copied when pushed in vectors. goes wrong. include class declaration , constructor , operators.

instruction.hpp

class instruction  {   private:       unsigned int param_size;     const float max_angle, min_angle;     bool micro_mutated;   protected:     const std::string body_part;     std::vector<parameter <float> > parameters;   public:     instruction(std::string name, float max, float min);     instruction operator=(const instruction& i);     bool operator<(const instruction& i) const;     //there few more functions irrelevant } 

instruction.cpp:

instruction::instruction(std::string name,float max, float min) : body_part (name), max_angle(max), min_angle(min) {}  instruction instruction::operator=(const instruction& i) {   (*this) = i;   return (*this); }  bool instruction::operator<(const instruction& i) const {   return body_part < i.body_part; } 

the reason why created assignment operator (which honest i've never done before) because when trying push_back instructions, compiler complained not being able instantiate "from here" instructions , thought had constant members. without members being constant, worked fine, sorting. weird part. if remove std::sort, above code works, not time. times crashed after while, times won't crash. moment include sorting, crashes straight away. can please ?

don't forget rule of threes: if have 1 of copy construct, copy assignment operator, , destructor, should have all of them.

however, copy assignment operator infinite loop; calls itself. operator= used whenever have of form: instruction &=instruction&. (*this) = i is.

my question this: why things constant? having members constant means cannot copy object (unless use const-cast) copy assignment. can copy construct them, that's it.

is there reason members constant? , if so, shouldn't copying these objects assignment. 2 mutually exclusive.

if need member constant, unchangable outside activity (but not language-const prevents copying), should done proper accessor methods. provide users of class ways these values, not ways set them.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -