当使用对象的浅副本时,双重的免费错误...如何解决? [英] Double free errors when using shallow copies of objects... how to fix?

查看:119
本文介绍了当使用对象的浅副本时,双重的免费错误...如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从浅复制对象与原始对象中删除双(删除)错误。

How do I remove double (delete) errors from shallow copied object vs original object.

一个简单的示例:

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?

推荐答案

对于所有具有动态成员的对象,

For all objects with dynamic members, it is usually best to define your own copy and copy-assignment operations for just this reason.

关于大对象和昂贵的复制,引用计数是许多语言和模式用于规避指针所有权问题的技术。请注意,在这种情况下,一个对象的所有副本都指向同一个共享对象,因此对一个实例的共享对象的修改将对其他人可见。请参阅 boost shared_ptr 文档以获取更多信息。

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.

这篇关于当使用对象的浅副本时,双重的免费错误...如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆