That’s uhhh… I think it’s safe to say that my statement “you can’t rely on one or the other” will hold over a sufficient number of releases. This is one of the bugs in the optimization which @squeek502 was referring to. And linked to.
This conversation is getting a bit muddled, I think, between what the compiler is supposed to do, what it happens to do, and what aspects of program behavior should be considered semantics.
But it does illustrate why pass-by-const-pointer and pass-by-reference dont have identical semantics, and aren’t intended to. If you pass by const pointer, the address of the pointer will be the same as the value from which you took it, passing by reference there are no guarantees of that. That’s a semantic difference:
const Selfie = struct {
me: *Selfie = undefined,
pub fn compareToSelf(selfie: Selfie) bool {
return @intFromPtr(selfie.me) == @intFromPtr(&selfie);
}
pub fn compareToSelfPtr(selfie: *const Selfie) bool {
return @intFromPtr(selfie.me) == @intFromPtr(selfie);
}
};
test "self reference" {
var self = Selfie{};
selfie.me = &self;
// This must be true
expect(selfie.compareToSelfPtr());
// Anything can happen
_ = selfie.compareToSelf();
};
That’s an example of a semantic difference. Contrived, yes, but things which lie closely adjacent to this are the essence of the aliasing issue.
It’s quite clear that pass by reference is not supposed to have the C semantics of passing a struct, which is by value. It’s weird to find out that it apparently always does that at the moment, but I can’t imagine that situation continuing forever.
To quote Andrew from the other issue @squeek502 linked to:
Temporary workaround is to pass by const pointer instead. However, we don’t want Zig users to get used to doing this, or they will never kick the habit even when this issue is fixed, which is why I am making this a high priority issue, and denying any more requests to do the workaround in the standard library.
So do what you need to for your programs to work and run fast, but let’s not allow a transient bug to solidify into doctrine.