通过引用和值传递指针到函数,并使用指针链上的delete [英] Passing pointers to functions by reference vs. by value, and using delete on pointer chains

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

问题描述

假设我这样做:

  void func(int *& refptr)
{
* refptr = 7;
}

int * ptr = new int;
func(ptr);

现在,如果我离开引用操作符,将不会完成同样的事情在func ?任何一种方式,你在堆中访问相同的int值,所以是一种方式比另一种更好?应该参考运算符只在您尝试更改指针指向的位置时使用?我不清楚这一点,我的教授没有帮助。 :(



我的其他问题与删除操作符有关。假设我有:

  int ** ptr = new int *; 

ptr * = new int;

如果我想释放堆中分配的所有内存,我可以在ptr上使用delete一次,否则我必须删除ptr *然后删除ptr?



非常感谢。

解决方案

当然,通过引用传递一个指针允许你改变指针的指向,如果你想的话,你可以用一个双指针完成同样的事情。


$ b $

  / b 

/内存:free
int ** ptr = new int *;
//内存:为int分配的四个字节
ptr * = new int;
//内存:为int *分配的字节,为int
分配的四个字节

int,一个删除分配给int *的四个字节。


Let's say I do this:

void func ( int* & refptr)
{    
     *refptr = 7;
}

int* ptr = new int;
func( ptr );

Now, if I left off the reference operator, wouldn't the exact same thing be accomplished in func? Either way you are accessing the same int value in the heap, so is one way preferable to the other? Should the reference operator only be used when you are trying to change the location to which the pointer... points? I'm unclear on this and my professor is no help. :(

My other question has to do with the delete operator. Let's say I have:

int** ptr = new int*;

ptr* = new int;

If I wanted to deallocate all the memory allocated in the heap, could I just use delete once on ptr, or would I have to delete ptr* and then ptr?

Thank you so much.

解决方案

There is no benefit to passing pointers by reference, although it doesn't hurt, either. Naturally, passing a pointer by reference allows you to change where the pointer's pointing, if you want to. You could accomplish the same thing using a double pointer.

You'll need two deletes in your case. Here's what the memory will look like after your calls:

// Memory: free
int ** ptr = new int*;
// Memory: four bytes allocated for int*
ptr* = new int;
// Memory: four bytes allocated for int*, four bytes allocated for int

You need one delete for the four bytes allocated for int, one delete for the four bytes allocated for int*.

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

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