Operator = Overload with Const Variable in C++

前端 未结 6 1116
刺人心
刺人心 2020-12-31 23:48

I was wondering if you guys could help me.

Here are my .h:

Class Doctor {
   const string name;
   public:
       Doctor();
       Doctor(string nam         


        
6条回答
  •  旧时难觅i
    2021-01-01 00:35

    The standard way to define the assignment constructor correctly so that it is exception safe is to define it in terms of the copy constructor.

    class Doctor
    {
        public:
            Doctor& operator=(Doctor const& rhs)
            {
                if (this != &rhs)
                {
                    Doctor  tmp(rhs);  // Use copy constructor here
                    this->swap(tmp);   // Now Swap
                }
                return *this;
            }
            void swap(Doctor& rhs) throws()
            {
                std::swap(.....); // swap each member variable.
            }
    };
    

    By doing it like this makes it exception safe.
    Note you just need to make the swap a no-throw method, this is relatively simple if you are using STL objects as they all define a no-throw swap just for this situation as does boost and all good libraries (so you should follow suite).

    If this going wrong they will go wrong in using the copy constructor. At this point you have not modified your own object as you are copy constructing into a temporary. Thus you are providing good exception safety as your object is still un-changed.

提交回复
热议问题