开发者

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

开发者 https://www.devze.com 2023-02-16 07:45 出处:网络
How do I remove double (delete) errors from shallow copied object vs original object. A simple example:

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, resu开发者_如何学编程lting 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.


Patient: Doctor, it hurts when I do this!
Doctor: Don't do that.

Chances are at least 100:1 that you can write your code just fine without dealing with a raw pointer. Depending on the situation, you may need a smart pointer or you may need a collection, but the chances that you need a pointer seem quite remote.

Instead of asking about how to fix what you're doing, you'd be much better off telling us what you're trying to accomplish, so we can tell you about how to do that.


The question "How do I avoid double delete from shallow copied objects?" should really be "How do I avoid shallow copies, when I don't want that?".

Some options are:
- avoid raw pointers to allocated memory
- don't copy the objects! :-)
- manage the memory outside of the objects
- use a smart pointer
- implement deep copying

Your choice depends on what you are actually using your objects for.

0

精彩评论

暂无评论...
验证码 换一张
取 消