Jdc1197
Jdc1197

Reputation: 255

Memory usage when passing by reference?

I have an object (i.e. an image) that takes up 1MB of memory. I pass this image into a function, which modifies it. If I pass this image into the function by reference, would the entire 1MB be copied, or just its place in memory?

Upvotes: 3

Views: 5015

Answers (5)

zeacuss
zeacuss

Reputation: 2623

just the reference to the image object is sent to the function, not the whole image.

Upvotes: 1

ouah
ouah

Reputation: 145829

When you pass by reference you don't copy the object but only the reference to the object. That's the whole point of passing by reference.

Upvotes: 2

Martin Beckett
Martin Beckett

Reputation: 96119

No just a pointer - a reference is just a pointer with fancy syntax so it doesn't scare the children.

Upvotes: 13

rerun
rerun

Reputation: 25495

Passing by reference creates an alias to the object. The only memory used is the stack space allocated to hold the alias.

Upvotes: 6

prelic
prelic

Reputation: 4518

Just the reference location to the object would be passed onto the stack.

Just so we're clear here, this only applies to C++. In C, you always pass by value. You can mimic pass-by-reference by passing in pointer locations (which is how references in C++ work anyway, if I'm not mistaken).

Upvotes: 2

Related Questions