If I pass by value as an argument to a particular function, then will that function deallocate memory of this parameter when the function execution ends开发者_如何学运维?
If I pass a pointer or reference as argument, what happens if function deallocates memory of the pointer argument? Will it affect to the variable outside of function?
In the first case memory will be "deallocated" (actually stack pointer will be increased). If this is not POD type variable destructor is called, so the memory will be deallocated from heap if it was allocated there.
In the second case value referenced by pointer won't be deallocated - only memory for pointer will be deallocated.
For point 1, it depends on the type of argument. Passing e.g. a 'string' by value will do an implicit copy, and the memory that copy uses will be deallocated when the variable (function parameter) goes out of scope. This won't automatically happen for your own types - you'll need to set up construction and destruction properly.
For the second - yeah, deallocating using a pointer will affect the memory it addresses - both inside the function and outside.
To clarify the second point:
void func(char *someMemory) {
delete[] someMemory;
}
//...
char *myArray = new char[100];
func(myArray);
...will delete the allocated memory - using myArray
after the call to func is BAD.
If you pass a value or a pointer on the stack the memory required to hold that value is allocated on the stack...
The way the stack works you can keep "allocating" more memory but it has to be "freed" in reverse order.
So:
void f(int *ptr, int v)
{
// Do something
}
When you call f() the value of ptr and v are "pushed" on the stack, that is enough memory is magically created to hold those values. When the function returns the stack is adjusted the other way, in a sense they are "popped" from the stack.
This pushing and popping has no effect on the original pointer or value. So:
ptr++;
Will not effect the value of the pointer held by the calling function.
If you dereference, *ptr, the pointer you are accessing the same data that is visible from outside the function. If you free() the pointer this impacts what is seen from outside the function. So when you pass a pointer there are no copies made of the original data the pointer is pointing to but there is a copy made of the actual pointer. The pointer is passed by value.
精彩评论