This is an interview question I saw from here:
http://www.careercup.com/question?id=1707701
Want to know more about this .thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Shallow copy causes a problem (primarily) when you have “remote ownership”. The most common form is a pointer to data that’s owned by the object so when the object is destroyed the data it owns gets destroyed as well. One place many people run into this is the inevitable string class:
This will compile just fine. Under these exact circumstances, it might even seem to run fine as well. That doesn’t mean it’s really right though. When we assign
stot, the pointer gets copied, but what it points at does not get copied. We have two objects both containing pointers to the same buffer. When one of them gets destroyed, it deletes the associated buffer for the data. Then we have a dangling pointer — it’s still trying to refer to the buffer, but the buffer no longer exists. When the second object gets destroyed, it’ll try to free the same memory again — but since it’s already been freed, that leads to undefined behavior (I.e., anything can happen, and something bad usually will).There are two common alternatives to shallow copying. One is a “deep” copy, in which we overload the copy constructor and assignment operator for the class, and in them when we copy/assign the object, we allocate a new buffer and copy the contents of the old buffer to the new one.
The second is reference counting. Instead of a “raw” pointer to the buffer, we use a “smart” pointer to the buffer. The smart pointer keeps track of how many objects refer to the buffer and only frees the buffer itself when nothing refers to it any more.
Neither is entirely perfect: deep copying can be slow and use a lot of memory, especially if there’s a lot of data involved. Reference counting can be slow in multi-threaded environments — since the reference count can be accessed from multiple threads, you have to protect it to assure only one thread modifies it a time (which is usually at least an order of magnitude slower than a normal increment/decrement).