C++ why you need to have a good copy constructor

shallow copy vs deep copy

Do you see any problem?

If you just compile and run, you will not notice a big problem here.

However, if you compile with address sanitizer with an option of -fsanitize=address then you will see a big problem of double free !!!

This because basically, a default constructor will just copy the value of a member

So, addresses of foo.p and bar.p are same and deleting same address twice will end up with a double free.

To avoid this, you need to create a good copy constructor like

This will allocate a separate memory location for p and performs a deep copy.



Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store