Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing code duplication between operator= and the copy constructor

I have a class that requires a non-default copy constructor and assignment operator (it contains lists of pointers). Is there any general way to reduce the code duplication between the copy constructor and the assignment operator?

like image 269
Dan Hook Avatar asked Sep 25 '09 12:09

Dan Hook


People also ask

What is difference between copy constructor and constructor?

Constructor: It is a method which has the same name as the class which is used to create an instance of the class. Copy Constructor: Used to create an object by copying variables from another object of the same class.

What is the advantage of copy constructor?

Advantages of Copy ConstructorIf a field declared as final, the copy constructor can change it. There is no need for typecasting. Its use is easier if an object has several fields. Addition of field to the class is easy because of it.


1 Answers

There's no "general way" for writing custom copy constructors and assignment operators that works in all cases. But there's an idiom called "copy-&-swap":

 class myclass
 {
    ...
 public:
    myclass(myclass const&);

    void swap(myclass & with);

    myclass& operator=(myclass copy) {
        this->swap(copy);
        return *this;
    }

    ...
};

It's useful in many (but not all) situations. Sometimes you can do better. A vector or a string could have a better assignment which reuses allocated storage if it was large enough.

like image 53
sellibitze Avatar answered Oct 08 '22 04:10

sellibitze