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:
You need one delete for the four bytes allocated for int, one delete for the four bytes allocated for int*.