Default copy constructor & its problems [duplicate]
开发者_Go百科Possible Duplicate:
What is The Rule of Three?
Why is it recommended to provide implementation of copy constructor instead of using compiler provided "default copy constructor" ?
If your class contains pointer members, which are dynamically allocated then you need to provide your own version of copy construcor because the default version just makes a shallow copy of them.
It's not.
The default copy constructor is perfect in 99.9% of cases.
The exception of classes with owned pointers. Here the shallow copy of the default copy constructor does not work as expected for beginners.
But then you should never have pointers in your class so it becomes a non issue. To make this clear any owned pointers should be contained in a smart pointer (or container type) object. So it is a non issue.
If you are writing a smart pointer or container like object, then you need to implement the rule of three.
精彩评论