rule of three - C++ : copy-and-swap idiom, alternative constructor -
nb: question follows a previous one, hope okay still ask new question.
i trying implement "three , half big rule" (copy-and-swap idiom) tree class, looks this:
class tree { friend void swap(tree &first, tree &second); // swap function public: tree(const double &a, const double &b, int depth); // public constructor (derived default (private) constructor) tree(const tree &other); // copy constructor ~tree(); // destructor tree & operator=(tree other); // copy-assignement operator private: tree(double *a, double *b, int depth, int maxdepth); // default (private) constructor double *a, *b; int depth, maxdepth; tree *leftchild, *rightchild; };
i have been trying follow this guideline. here copy-assignment operator looks like:
tree & tree::operator=(tree other) { swap(*this, other); return *this; }
i having hard time getting public constructor work. suggested like:
tree::tree(const double &a, const double &b, int depth) { double atemp(a), btemp(b); swap(*this, tree(&atemp, &btemp, depth, depth)); }
i not sure idea works. in case following error compiler:
invalid initialization of non-const reference of type 'tree&' rvalue of type 'tree' in passing argument 2 of 'void swap(tree&, tree&)'
i tried following idea instead, thought work:
tree::tree(const double &a, const double &b, int depth) { double atemp(a), btemp(b); *this = tree(&atemp, &btemp, depth, depth); }
but not seem working either. think problem when call copy-assignment operator (*this = tree(&atemp, &btemp, depth, depth)
), copy constructor should called (since argument of copy-assignement operator passed value), seems not happening. not understand why.
thanks in advance helping!
invalid initialization of non-const reference of type 'tree&' rvalue of type 'tree' in passing argument 2 of 'void swap(tree&, tree&)'
c++ not allow passing anonymous objects non-const
reference. intent prevent callers accidentally throwing away results of functions write reference argument.
you instead do:
tree::tree(const double &a, const double &b, int depth) { double atemp(a), btemp(b); tree temp(&atemp, &btemp, depth, depth); swap(*this, temp); }
but not seem working either. think problem when call copy-assignment operator (*this = tree(&atemp, &btemp, depth, depth)), copy constructor should called (since argument of copy-assignement operator passed value), seems not happening. not understand why.
how determining it's not working? compiler might elide away copy avoid doing unnecessary work. (that why copy-assignment operator takes argument value.)
btw, if compiler supports c++11, use delegating constructors instead.
Comments
Post a Comment