Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove implicit cast from T to *const T #1465

Closed
andrewrk opened this issue Sep 3, 2018 · 1 comment
Closed

remove implicit cast from T to *const T #1465

andrewrk opened this issue Sep 3, 2018 · 1 comment
Labels
accepted This proposal is planned. proposal This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone

Comments

@andrewrk
Copy link
Member

andrewrk commented Sep 3, 2018

Now that #733 landed, T to *const T is less important. One might even make the case that such a cast is dangerous.

@andrewrk andrewrk added the proposal This issue suggests modifications. If it also has the "accepted" label then it is planned. label Sep 3, 2018
@andrewrk andrewrk added this to the 0.4.0 milestone Sep 3, 2018
@ghost
Copy link

ghost commented Sep 4, 2018

here are some examples I threw together of how this implicit cast can bite you in other parts of code:

const Contents = struct{
  value: u32,
};

const Container = struct{
  contents: Contents,
};

test "LHS: value, RHS: value" {
  var container = Container{ .contents = Contents{ .value = 1 } };
  var x: Contents = undefined;
  x = container.contents;
  container.contents.value = 2;
  std.debug.assert(x.value == 1);
}

test "LHS: pointer, RHS: value" {
  var container = Container{ .contents = Contents{ .value = 1 } };
  var x: *const Contents = undefined; // this is the only line that has changed!
  x = container.contents; // this line now has very different meaning
  container.contents.value = 2;
  std.debug.assert(x.value == 2);
}

/////////////

fn returnCopy() Contents {
  var container = Container{ .contents = Contents{ .value = 1 } };
  return container.contents; // returning copy
}

fn returnPointer() *const Contents {
  var container = Container{ .contents = Contents{ .value = 1 } };
  return container.contents; // looks the same, but very different meaning!
}

fn anotherFunction() void {
  var container = Container{ .contents = Contents{ .value = 999 } };
}

test "function returning copy" {
  const contents = returnCopy();
  anotherFunction();
  std.debug.assert(contents.value == 1);
}

test "function returning pointer" {
  const contents = returnPointer();
  anotherFunction();
  std.debug.warn("{}\n", contents.value); // this is garbage
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
accepted This proposal is planned. proposal This issue suggests modifications. If it also has the "accepted" label then it is planned.
Projects
None yet
Development

No branches or pull requests

1 participant