Double free errors when using small copies of objects ... how to fix?

How to remove double (delete) errors from a small copied object and the 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 to get a general solution, because going through objects is a trivial thing, and something as naive as this, which leads to a terrifying / terrific mistake, is just "awesome."

I suspect there are many ways around (some of which I can even come up with), but I was curious if there is any general (applicable almost everywhere) way to solve this problem?

+3
source share
4 answers

.

"" , - , . , , . . boost shared_ptr.

+2

, apointer , , .

+5

: , , ! : .

100: 1, , . , , , , .

, , , , , , , .

+3

The question "How to avoid double deletion from small copied objects?" should really be "How to avoid small copies when I don't want it?".

Some parameters:
- avoid raw pointers to allocated memory

- do not copy objects! :-)
- manage memory outside objects
- use a smart pointer
- perform deep copying

Your choice depends on what you actually use your objects on.

+1
source