对作为函数参数传递的指针使用delete [英] Using delete on pointers passed as function arguments

查看:996
本文介绍了对作为函数参数传递的指针使用delete的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

删除已作为函数参数传递的指针是否正常(和合法):

Is it okay( and legal) to delete a pointer that has been passed as a function argument such as this:

#include<iostream>

class test_class{
public:
    test_class():h(9){}
    int h;
    ~test_class(){std::cout<<"deleted";}
};

void delete_test(test_class* pointer_2){
    delete pointer_2;
}

int main(){
    test_class* pointer_1;

    while(true){
        pointer_1 = new test_class;

        //std::cout<<pointer_1->h;

        delete_test(pointer_1);
    }
}

现在编译正常,但我只是想确保它总是这样。

This compiles fine now, but I just want to make sure it'll always be that way.

推荐答案

它将始终无错编译。

根据你的程序的具体情况,将指针传递给函数并在函数中删除它是一件好事。

Whether it's a good thing to pass a pointer into a function and delete it in that function is potentially another story, depending on the specifics of your program.

你需要考虑的主要思想是指向数据的所有权。当你传递那个指针,调用函数是否拥有传递的数据的所有权?即它是唯一的地方,这个数据可以参考?你放弃了指向数据的所有权,没有机会调用函数将再次引用数据?

The main idea you need to consider is that of "ownership" of the pointed-to data. When you pass that pointer, does the calling function have ownership of the data being passed in? i.e. is it in the only place that this data can be referenced from? Are you giving up ownership of the pointed-to-data, with no chance that the calling function is ever going to reference the data again? If so, then you must delete it.

如果调用函数可能再次引用数据,那么你不能删除它。

If the calling function might reference the data again, then you must not delete it.

如果通过各种数据结构存在对数据的其他引用,那么删除此数据是不安全的,除非您的代码中有某些原则,以确保您不会再从这些位置引用数据。这很难做,而且是许多编程错误的根源。

If there are other references to the data through various data structures, then it's not safe to delete this data unless you have some discipline in place in your code to ensure that you will never reference the data again from those places. This is hard to do, and is the source of many programming bugs.

C ++ tr1的shared_ptr<>是一个智能指针,有助于在这些情况下 - 它通过保持引用计数跟踪对数据的引用的数量来管理这个所有权概念。如果引用计数为1,则有1个清除所有者。如果引用计数大于1,则会共享所有权。如果引用计数为0,则不再有对数据的引用,并且shared_ptr<>将在shared_ptr<>时删除它。析构函数被调用。

C++ tr1's shared_ptr<> is a smart pointer that helps in these kinds of situations - it manages this ownership concept by keeping a reference count that tracks the number of references to the data. If the reference count is 1, then there is 1 clear owner. If the reference count is larger than 1, then ownership is shared. If the reference count is 0, then there are no more references to the data, and shared_ptr<> will delete it when the shared_ptr<> destructor is called.

这篇关于对作为函数参数传递的指针使用delete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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