swift - Accessing a `var` passed as `inout` is undefined behavior? -


from documentation inout parameters:

in-out parameters passed follows:

  1. when function called, value of argument copied.
  2. in body of function, copy modified.
  3. when function returns, copy’s value assigned original argument.

from description, assume modification of variable passed inout parameter, within scope in passed inout, meaningless, since original variable guaranteed overwritten after call returns. contrived example:

var x: int = 5  ({ (inoutx: inout int) in     inoutx = 7     x = 6 })(&x)  print(x) // expecting "7" 

the original variable x accessible through mutating capture, can still assigned to. expected printout "7", since value of inoutx @ end of function call. if run in swift 4 repl, "6"!

the documentation sheds light on behavior:

as optimization, when argument value stored @ physical address in memory, same memory location used both inside , outside function body.

but follows statement inaccurate:

the optimized behavior known call reference; satisfies of requirements of copy-in copy-out model while removing overhead of copying.

clearly, optimized behavior not satisfying call-by-value-result convention inout parameters claim conform to. documentation acknowledges this, in reverse, explaining why should not rely on call-by-reference behavior:

write code using model given copy-in copy-out, without depending on call-by-reference optimization, behaves correctly or without optimization.

do not access value passed in-out argument, if original argument available in current scope. when function returns, changes original overwritten value of copy. not depend on implementation of call-by-reference optimization try keep changes being overwritten.

what can gather then, inout parameters call-by-value-result, except when they're call-by-reference. and, based on how documentation doesn't want rely on call-by-reference semantics, can guess optimization not performed in well-defined set of cases. , if that's case, can conclude accessing variable passed inout parameter, within scope in inout, undefined behavior.

that's relatively unfortunate conclusion, , i'm left confused how unwilling documentation make it. why try present inout parameters obeying particular calling convention, when (aside setters or property observers) semantics of these calling conventions not observable in defined manner? it's confusing enough doubt own conclusion here, , comes question: understanding correct?


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -