Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are structures passed by value?

The "Objective-C for Java Programmers, Part 1" intro by David Chisnall states that

Unlike objects, which are always passed by reference, structures are commonly passed by value.

I am very new to Objective-C (coming from C++) and so I am having trouble understanding this. In C++, I could pass a structure either by a pointer or by reference, but never by value (probably because it is very inefficient).

How does Objective-C accomplish this? Does it really push all structure members, one by one, in a stack-like manner?

What happens if the structure is made of large/complex objects?

like image 627
Very Objective Avatar asked Mar 01 '26 06:03

Very Objective


2 Answers

Yes it makes a copy of the whole structure and this one is passed to the calling function, and any modification made won't affect the original one. And the disadvantage is of course because it is slow, but also consumes twice space.

like image 132
NiVeR Avatar answered Mar 03 '26 20:03

NiVeR


It copies all the structure members to the stack. Remember, that complex objects in the structure are stored by pointers to it, so when you copy structure, you have copy and copies of points to complex types. Of course copy of pointer points to the same place in memory as original, so you perform actions on original objects then.

This approach when you have copies of primitive types and original complex objects leads to unmaintainable mess, even when you know what you are doing at the moment.

like image 44
pro_metedor Avatar answered Mar 03 '26 20:03

pro_metedor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!