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
// something similar to this
Foo(const Foo& other) : p(other.p) {}
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
Foo(const Foo &other) {
std::cout << "copy constructor\n";
if (other.p != nullptr)
p = new int(*other.p);
}
This will allocate a separate memory location for p and performs a deep copy.