Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...