Function Variables

When I do this:
1
2
3
4
void function(std::string thestring)
{
//random code
}


Is thestring cleared from the memory when the function is completed?
Thanks in advance.
Last edited on
The object that the function plays with is, yes; it's a copy of the original that was passed in, though, and that original still exists.
Ok, thank you. What if that is the original?
It's not the original. When you pass a variable like this:

1
2
3
std::String bobOnSticks;

function(bobOnSticks);


function doesn't get the original. It gets a copy. This is called "pass by value".

If function takes a pointer, and you pass it like this:

1
2
3
std::string bobOnSticks;
std::string* pointerToBobOnSticks = &bobOnSticks;
function(pointerToBobOnSticks);

the function is passed a copy of the pointer, and can use it to directly mess with the original, and when it is finished the copy of the pointer is destroyed but any changes to bobOnSticks happened to the original. This is "pass by pointer", which you will have noticed is actually the same as "pass by value", but because it's a pointer, we can use it to get access to the original.

If the function takes a reference variable, which means it will have a prototype like this:

void function(std:string& inputString);

then when we do this
1
2
3
std::string bobOnSticks;

function(bobOnSticks);

the function does not get a copy. It gets the original, and anything it does to it happens to the original, and the original is not destroyed when the function ends. This is "pass by reference".



Last edited on
Okay, thanks.
Topic archived. No new replies allowed.