[swift-users] inout params seem to have undefined behavior
zh ao
owenzx at gmail.com
Sat Jun 11 21:18:40 CDT 2016
inout says it will copy into the function and copy back after the function
is finished. But the order is unknown. So I think the example,
print(acopy) // prints "[1, 2, 99]" (e.g. a let variable changed!)
i
s a bug as the value changed inside of the function, before the function
returns.
Swift doc:
“In-out parameters are passed as follows:
1
.
When the function is called, the value of the argument is copied.
2
.
In the body of the function, the copy is modified.
3
.
When the function returns, the copy’s value is assigned to the original
argument.”
摘录来自: Apple Inc. “The Swift Programming Language (Swift 2.2)”。 iBooks.
Zhaoxin
On Sun, Jun 12, 2016 at 9:27 AM, Karl Pickett via swift-users <
swift-users at swift.org> wrote:
> Wow there are some real doozy inout code examples in there, showing
> aliasing much more fun than my snippet. Unfortunately I can't
> understand anything else the doc is talking about. I guess I'll just
> say a prayer and throw salt over my shoulder if using inout.
>
> On Sat, Jun 11, 2016 at 6:05 PM, Brent Royal-Gordon
> <brent at architechies.com> wrote:
> >> My recollection is that in Swift the subscript operator (`arr[2]` in
> this case) can refer to the setter xor the getter, but not both within the
> same statement.
> >
> > Quite to the contrary. Rather than using the setter directly, Swift
> often uses `materializeForSet`, a combined get-and-set operation which is
> much more efficient, particularly when assigning directly into arrays. To
> keep from having to use very slow access all the time, it imposes a rule
> (which is not and cannot be enforced by the compiler) that you can't hold
> two mutable references to overlapping storage simultaneously, or they may
> do strange things like lose some of the writes you make.
> >
> > Here's an old design document discussing some things in this area: <
> https://github.com/apple/swift/blob/73841a643c087e854a2f62c7e073317bd43af310/docs/proposals/Accessors.rst>
> I'm not sure how authoritative it is, but it might give you an idea of
> what's going on.
> >
> > --
> > Brent Royal-Gordon
> > Architechies
> >
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160612/915201a9/attachment.html>
More information about the swift-users
mailing list