I'm reading the book 'C++ Without Fear 2nd Edu' and I'm a little confused on the subject of shallow copies.
The book says the problems can arise if you make a shallow copy of an object and something happens to the original, goes out of scope, is deleted, etc... I don't get it. When a simple copy is made doesn't the new object get a member to member COPY of the value? The way the book makes it sound is as if the new object isn't a copy at all, it's just another pointer or reference to the same old object. That's the only way I see that something happening to the original object would affect the new. What am I missing here? Thanks.

Recommended Answers

All 2 Replies

Create a class with a pointer member. Allocate some memory with some data in it for the pointer to point to. In the class destructor, deallocate that memory.

Now create a copy of that class. The pointer is copied. This is a "shallow" copy; you have copied only the pointer to the data; you have not copied the data.

You've got two objects containing pointers, both pointing to the same allocated memory. Destruct one of those objects. The memory being pointed to is deallocated. So what is the remaining object pointing to? Deallocated memory. This is very bad. This is the problem.

What if your class is very simple and doesn't have pointers to anything? Then this problem doesn't exist.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.