The example in official document explain value type as this that the copy operation will occurred in assignment:
// Value type example
struct S { var data: Int = -1 }
var a = S()
var b = a // a is copied to b
a.data = 42 // Changes a, not b
I have a question in the line
var a = S()
This line is also a assignment ,But from the code comment this line seems will not make a copy operation.
Is this line will also cause a copy operation or not? ( e.g: system malloc a S() in memory address C, and then copy to another address B, and the var a will point to this address B )?
CodePudding user response:
It won't cause a copy operation. Since this is a struct
there is no need for a malloc (or it's Swift equivalent swift_allocObject
). It will just allocate an Int size from the stack by changing stack pointer.
See the godbolt here
CodePudding user response:
The line var a = S()
will assign the variable named a
to a new instance of struct S. Therefore, there is not any copy here. If S was of type class, this would not change anything: no copy. With a let
assignment instead of var
, there would be no copy. This is a direct assignment of a new instance to a new variable name.
Remember that when dealing with a struct object, like with any value type object, swift makes a copy only to avoid having two references to the same object. The line var a = S()
does not create more than one reference to the object, therefore there is no need to copy anything.