In writing a copy constructor for a class that holds a pointer to dynamically allocated memory, I have a question.
How can I specify that I want the value of the pointer of the copied from object to be copied to the pointer of the copied to object. Obviously something like this doesn't work...
*foo = *bar.foo;
because, the bar object is being deleted (the purpose of copying the object in the first place), and this just has the copied to object's foo point to the same place.
What is the solution here? How can I take the value of the dynamically allocated memory, and copy it to a different address?
The idea of "copying a pointer", when taken literally, is nothing more than a simple assignment. int x = 5; int* p1 = &x; int* p2 = p1; // there, we copied the pointer. In this case, both p1 and p2 point to the same data - the int variable x .
Copying a pointer does not copy the corresponding object, leading to surprises if two pointers inadvertently points to the same object. Destroying a pointer does not destroy its object, leading to memory leaks.
Technically, you could write a constructor that takes a pointer (although it's technically not a copy constructor in that case, based on the wording of the spec). However, this prevents you from using non-addressable results.
You allocate new object
class Foo
{
Foo(const Foo& other)
{
// deep copy
p = new int(*other.p);
// shallow copy (they both point to same object)
p = other.p;
}
private:
int* p;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With