How do I remove double (delete) errors from shallow copied object vs original object.
A simple example:
class INT
{
int *p; //dynamic.
//define here fancy constructors etc.
set(int i){ p=new int; p=i;}
~INT();
}
INT::~INT()
{
if(p) delete p;
}
void somefunction(INT a)
{
//done some stuff ,e.g. call some display function
}
//note here, that a destructor will be called, and a.p will vanish.
int main(void)
{
INT a; a.set(2);
somefunction(a);//shallow copy
}
//CRASH BOOM BOOM!
I would like a generic solution, because passing objects is a trivial thing, and something as naive as this, resulting into a horrific/terrific error is just 'awesome'.
I suspect there are many ways around this (some of which even I can think of), but I was curious if there is any generic (applicable almost everywhere) way of solving this problem?
Whenever you have apointer object inside your class then you need to declare your own copy constructor and assignment operator method to avoid shallow copy problem. Look ate this link for mor info on this
For all objects with dynamic members, it is usually best to define your own copy and copy-assignment operations for just this reason.
Regarding 'big' objects and expensive copying, reference counting is a technique employed by many languages and patterns to circumvent this problem of pointer ownership. Note that all copies of an object point to the same shared object in this case, so a modification of the shared object from one instance will be visible to others. See the boost shared_ptr documentation for more info.
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