[swift-users] non-mutating func that still mutates a struct, compiler not aware

Raphael Sebbe raphael at creaceed.com
Thu Aug 4 03:25:08 CDT 2016

In the example below, solve is a non-mutating func within struct type
Matrix, that uses an Array<T> to store its values.

This function mutates self, even though it's declared as non-mutating.

My understanding is that the compiler doesn't make a real copy in the acopy
=  self instruction, and then provides that contents to the mx_gels_
function which modifies the memory contents.

public func solve(rhs b: Matrix<T>) -> Matrix<T>? {

// ...

var acopy = self

// ...

T.mx_gels_(&trans, &m, &n, &nrhs, UnsafeMutablePointer<T>(acopy.values),
&lda, UnsafeMutablePointer<T>(x.values), &ldb,
&lwork, &status);

// ...


Is this expected? I mean, I can force a real copy of course, but value
semantics would suggest the code above is correct and wouldn't need that.
Shouldn't the cast trigger the copy somehow? Or is there a better way of
expressing this operation? Thx.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160804/822fafb1/attachment.html>

More information about the swift-users mailing list