在哪些情况下删除指针 [英] In Which Situations To Delete A Pointer

查看:200
本文介绍了在哪些情况下删除指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的以下问题是关于内存管理。我有一个int变量没有动态分配在类中,让我们说invar1。我把这个int的内存地址传递给另一个类构造函数。该类执行此操作:

 类ex1 {
ex1(int * p_intvar1)
{
ptoint = p_intvar1;
}

int * ptoint;
};

我应该删除ptoint吗?因为它有一个未动态分配的int地址,我以为我不需要删除它。



再次声明一个对象到一个类with new operator:

  objtoclass = new ex1(); 

我将此传递给另一个类:

  class ex2 {
ex2(ex1 * p_obj)
{
obj = p_obj;
}

ex1 * obj;
};

当我已经删除objtoclass时,应该删除obj吗?



谢谢!

解决方案


因为它有一个非动态分配的int我认为我不需要删除它。


更正。



< >

当我已经删除objtoclass时,应该删除obj吗?


b
$ b

回想一下,你并没有真正删除指针;你使用指针来删除他们指向的东西。因此,如果您同时写入 delete obj delete objtoclass ,因为两个指针指向同一个对象, d。删除该对象两次。



我会提醒你这是一个很容易的错误,你的 ex2 类,其中该指向对象的所有权语义不完全清楚。您可以考虑使用智能指针实现来消除风险。


My following question is on memory management. I have for example an int variable not allocated dynamically in a class, let's say invar1. And I'm passing the memory address of this int to another classes constructor. That class does this:

class ex1{
    ex1(int* p_intvar1)
    {
       ptoint = p_intvar1;
    }

    int* ptoint;
};

Should I delete ptoint? Because it has the address of an undynamically allocated int, I thought I don't need to delete it.

And again I declare an object to a class with new operator:

objtoclass = new ex1();

And I pass this to another class:

class ex2{
    ex2(ex1* p_obj)
    {
       obj = p_obj;
    }

    ex1* obj;
};

Should I delete obj when I'm already deleting objtoclass?

Thanks!

解决方案

Because it has the address of an undynamically allocated int I thought I don't need to delete it.

Correct.

Should I delete obj when I'm already deleting objtoclass?

No.

Recall that you're not actually deleting pointers; you're using pointers to delete the thing they point to. As such, if you wrote both delete obj and delete objtoclass, because both pointers point to the same object, you'd be deleting that object twice.

I would caution you that this is a very easy mistake to make with your ex2 class, in which the ownership semantics of that pointed-to object are not entirely clear. You might consider using a smart pointer implementation to remove risk.

这篇关于在哪些情况下删除指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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